switch statement to compare values greater or less than a number - javascript

I want to use the switch statement in some simple code i'm writing.
I'm trying to compare the variable in the parenthesis with values either < 13 or >= 13.
Is this possible using Switch?
var age = prompt("Enter you age");
switch (age) {
case <13:
alert("You must be 13 or older to play");
break;
case >=13:
alert("You are old enough to play");
break;
}

Directly it's not possible but indirectly you can do this
Try like this
switch (true) {
case (age < 13):
alert("You must be 13 or older to play");
break;
case (age >= 13):
alert("You are old enough to play");
break;
}
Here switch will always try to find true value. the case which will return first true it'll switch to that.
Suppose if age is less then 13 that's means that case will have true then it'll switch to that case.

Instead of switch you can easily to the same thing if else right?
if(age<13)
alert("You must be 13 or older to play");
else
alert("You are old enough to play");

This worked in my case:
var enteredAge = prompt("Enter your age");
let ageMoreThan13 = parseInt(enteredAge) >= 13;
let ageLessThan13 = parseInt(enteredAge) < 13;
switch (ageMoreThan13 || ageLessThan13) {
case ageLessThan13:
alert("You must be 13 or older to play");
break;
case ageMoreThan13:
alert("You are old enough to play");
break;
}

Instead of switch use nested if else like this:
if (x > 10) {
disp ('x is greater than 10')
}
else if (x < 10){
disp ('x is less than 10')
}
else
{
disp ('error')
}

You may use a conditional (ternary) operator instead. It takes a condition followed by a question mark (?), then an expression to execute if the condition is true and another if it is false.
This operator is frequently used as a shortcut for the if statement.
age >= 13 ? "You are old enough to play" : "You must be 13 or older to play";

It might be a bit silly to do this with a switch-case, but I added an answer where using switch-case, just for completeness.
var age = prompt("Enter you age");
switch (age) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
alert("You must be 13 or older to play");
break;
default:
alert("You are old enough to play");
break;
}

Related

Switch statement with numeric values

Trying simple switch with random number.
It does not seem to work. Always getting to default case.
var x = 0;
x = (Math.random() * 10 + 1);
switch(x) {
case x >= 5:
console.log("the number is bigger than 5");
break;
case x <= 5:
console.log("the number is smaller than 5");
break;
default:
console.log("strange number");
}
console.log(x);
The output is always similar to that:
strange number
5.922413225153608
That's just not how switch statements work in JavaScript,1 what you're looking for there is an if/else if/else series instead:
if (x >= 5) {
console.log("the number is bigger than 5");
} else if (x <= 5) {
console.log("the number is smaller than 5");
} else {
console.log("strange number");
}
Two notes, though:
Your first and second cases both include 5; the first will win.
The only value for x that will reach the final else is NaN (or something that converts to NaN when converted to number), because NaN >= 5 and NaN <= 5 are both false.
In a comment you've said:
Thanks, the point is to practice switch.
If so, you'll either have to do the thing below (which probably isn't what your instructor wanted), or limit the range of values, because the cases of a switch are tested for exact match.
For instance, if you changed your code only allow integers, you could use cases with fall-through:
var x = 0;
x = Math.floor(Math.random() * 10 + 1); // Note change: Only integers
switch(x) {
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
console.log("the number is bigger than 5");
break;
case 1:
case 2:
case 3:
case 4:
console.log("the number is smaller than 5");
break;
default:
console.log("strange number");
}
console.log(x);
That makes use of the fact that cases fall through to the following case when you don't use break.
But you can't do that with your original x, because there are just too many floating-point values in the range 1 <= x < 11 to list.
JavaScript's switch does have a feature that makes it possible to use switch here, but an if/else if/else is almost certainly a better choice. Purely for completeness:
// PROBABLY NOT A GOOD IDEA
switch (true) {
case x >= 5:
console.log("the number is bigger than 5");
break;
case x <= 5:
console.log("the number is smaller than 5");
break;
default:
console.log("strange number");
break;
}
That works because unlike many languages, JavaScript's switch cases are allowed to be expressions, and they're tested in the order in which they appear in the switch (other than default, of course), with the first matching case being used.
But again, probably not great to use in the real world except in very, very limited situations.
Between case and : you have to have a value.
x >= 5 and x <= 5 are going to give you true or false, which x will then be compared to. Since x will always be a number, it will never be true or false so you will always hit the default.
Use if/else if/else instead.
You can't do in thatway. You have to do
switch(true) {
case x >= 5:
console.log("the number is bigger than 5");
break;
case x <= 5:
console.log("the number is smaller than 5");
break;
default:
console.log("strange number");
}
While switch is using strict comparison and you have already in the case clause already a comparison, you could change your switch statement to
switch(true) {
and use the rest, you have.

Javascript combining AND && or || conditions in a switch statement

i’m creating a switch statement with javascript. I want to use the &&(AND) and ||(OR) conditions. I want var user = prompt to accept the inputs 14 or 13, or 14km or 13km, or 14 km or 13 km (with spaces) from user. I want to do the same for all the other cases.
How do I do this?
var user = prompt("How fast can you run per hour in kilometers (km)?").toUpperCase();
switch(user) {
case '14km':
if ( 14 || 13 == true) {
console.log("Woah!, your almost as fast as Usain Bolt!");
}
else {
console.log("RUN FASTER");
}
break;
case '12km':
if ( 12 || 11 == true) {
console.log("Your quick, but not as quick as me!");
}
else {
console.log("TOO SLOW");
}
break;
case '10km':
if ( 10 && 9 ) {
console.log("Average!");
}
break;
case '8km':
console.log("OK tortoise!");
break;
case '6km':
console.log("I think it's better you get some rest");
break;
default:
console.log("I didn't understand you? Can you repeat that please");
}
You can't combile conditions for switch case statements with && or ||, but you can specify several case statements for the same code, like this:
switch(user) {
case '14km':
case '13km':
case '14':
case '13':
console.log("Woah!, your almost as fast as Usain Bolt!");
break;
case '12km':
case '11km':
case '12':
case '11':
console.log("Your quick, but not as quick as me!");
break;
case '10km':
case '9km':
case '10':
case '9':
console.log("Average!");
break;
case '8km':
case '8':
console.log("OK tortoise!");
break;
case '6km':
case '6':
console.log("I think it's better you get some rest");
break;
default:
console.log("I didn't understand you? Can you repeat that please");
}
You could try a little trick with the switch statement code flow.
See this fiddle for an example to your question
https://jsfiddle.net/p51h5y4f/1/
See:
case 14:
case 13:
console.log("Woah!, your almost as fast as Usain Bolt!");
break;
case 12:
case 11:
console.log("Your quick, but not as quick as me!");
break;
In there, the user enters in an int to the box prompt, if it's 14 or 13, it goes into the first response, etc.
You can't use operator with switch. However you can evaluate multiple case in single block.
//Using regular expression extract on number
//So that you don't need to evaluate (14 km/14 KM/14km/14KM/14)
user = user.replace(/[^\d.]/g, '');
//Convert to number
user = parseInt(user , 10);
switch(user) {
case 14:
case 13:
console.log("Woah!, your almost as fast as Usain Bolt!");
break;
case 12:
case 11:
console.log("Your quick, but not as quick as me!");
break;
case 10:
case 9:
console.log("Average!");
break;
case 8:
console.log("OK tortoise!");
break;
case 6:
console.log("I think it's better you get some rest");
break;
default:
console.log("I didn't understand you? Can you repeat that please");
}
want var user = prompt to accept the inputs 14 or 13, or 14km or 13km,
or 14 km or 13 km (with spaces) from user
The user must input values within a html form . Then you get the values
document.getElementById('KM').value

Switch Case not showing correct results

Here is my script
var marks = 11;
switch (marks) {
case (marks < 20):
console.log('Yes Freaking Failed');
break;
case (marks > 20):
console.log('Ahh Its Ok');
break;
case (marks > 80):
console.log('Whooping');
break;
default:
console.log('Cant say u maybe Flunked');
break;
}
I think it should display 'Yes Freaking Failed' because the marks are less than 20. But it shows 'Cant say u maybe Flunked'
Why is that?
When you write
switch (x) {
case(y):
...
}
it's equivalent to testing
if (x == y) {
...
}
So
case (marks < 20):
means:
if (marks == (marks < 20)) {
You can't use case for range tests like this, you need to use a series of if/else if:
if (marks < 20) {
console.log('Yes Freaking Failed');
} else if (marks < 80) {
console.log('Ahh Its OK');
} else {
console.log('Whooping');
}
Also notice that if it worked the way you thought, it could never execute marks > 80, because that would also match marks > 20, and the first matching case is always executed.
There's no need for the Cant say u maybe flunked case, because there are no other possibilities.
Technically it's not possible. Javascript makes it so.
If you need to compare, use if/else if/else.
Switch cases are for when you know you will have specific values.
var marks=11;
switch(marks){
case (11):
console.log('It would go in here');
break;
case (42):
console.log('If equal to 42');
break;
case (80):
console.log('if equal to 80.');
break;
default:
console.log('Cant say u maybe Flunked');
break;
}
Your code is equivalent to:
var marks=11;
switch(marks){
case (true):
console.log('Yes Freaking Failed');
break;
case (false):
console.log('Ahh Its Ok');
break;
case (false):
console.log('Whooping');
break;
default:
console.log('Cant say u maybe Flunked');
break;
}
marks is not true and is not false - so switch goes to default.
when you use switch statement, you are evaluating marks and compare the values of marks with the cases. And you have the following cases: 1, 0, 0, default. It's because (marks<20) evaluates to true which is 1, and the other two are false, which is 0.
So you should do if and else if in your case.

Simple switch statement

var speed = prompt("Do you know how to type?");
speed = speed.toLowerCase();
if (speed === "yes" ) {
var howFast = prompt("what is your wpm?(the answer must be a number between 1 and 200");
switch(howFast) {
case (howFast <= 10):
console.log("you are a snail! practice and type at least 20 wpm, then try this again.");
break;
case (howFast <= 30):
console.log("you are still pretty slow, but you're getting there!");
break;
case (howFast <= 50):
console.log("you are getting there, keep trying");
break;
case (howFast <= 90):
console.log("WoW! Excellent job! Your tenacity has paid off");
break;
case (howFast > 90):
console.log("you are a megaracer! congratulations!");
break;
default:
console.log("DOES NOT COMPUTE... You're either superfast or playing around!");
}
} else { alert("learn how to type and comeback.");}
I am trying to code a simple switch statement in javascript to ask users their typing speed. To my dismay, when this code executes the final alert i get back is always the default case. Please tell me what I did wrong!
just change:
switch(howFast) {
..
to
switch(true) {
..
and it should work.
Demo:: jsFiddle
I got this working :
var speed = prompt("Do you know how to type?");
speed = speed.toLowerCase();
if (speed === "yes" ) {
var howFast = prompt("what is your wpm?(the answer must be a number between 1 and 200");
switch(true) {
case (parseInt(howFast) <= 10):
console.log("you are a snail! practice and type at least 20 wpm, then try this again.");
break;
case (parseInt(howFast) <= 30):
console.log("you are still pretty slow, but you're getting there!");
break;
case (parseInt(howFast) <= 50):
console.log("you are getting there, keep trying");
break;
case (parseInt(howFast) <= 90):
console.log("WoW! Excellent job! Your tenacity has paid off");
break;
case (parseInt(howFast) > 90):
console.log("you are a megaracer! congratulations!");
break;
default:
console.log("DOES NOT COMPUTE... You're either superfast or playing around!");
}
} else { alert("learn how to type and comeback.");}
jsFiddle: http://jsfiddle.net/kR4cy/6/
Hope it helps
Its a bit of a hack but you can do expressions in JS case statements like this:
var wpm = parseInt(howFast); // convert string to number first
switch(true)
{
case wpm >= 0 && wpm <= 10:
console.log('snail');
break;
case wpm > 10 && wpm <= 30:
console.log('slowpoke');
break;
// etc.
}
In this case, there isn't an expression that applies to each case, therefore, an if-else block makes more sense to use instead of switch.
From my experience, you cannot have operators in your switch case; you must have a definite value. In this case you should use an IF ELSE block even though the switch would look better.
Edit: I also found this answer from a similar question.
You need to convert the prompt response to an integer before you compare it, and you will need to change your switch to a set of IFs.
<script>
var speed = prompt("Do you know how to type?");
var howFast;
var logMessage;
speed = speed.toLowerCase();
if (speed === "yes" ) {
howFast = parseInt(prompt("what is your wpm?..."));
logMessage = "DOES NOT COMPUTE... You're either superfast or playing around!";
if (howFast <= 10)
logMessage = "you are a snail! practice and type at least 20 wpm, then try this again.";
if (howFast <= 30)
logMessage = "you are still pretty slow, but you're getting there!";
if (howFast <= 50)
logMessage = "you are getting there, keep trying";
if (howFast <= 90)
logMessage = "WoW! Excellent job! Your tenacity has paid off";
if (howFast > 90)
logMessage = "you are a megaracer! congratulations!";
console.log(logMessage);
} else {
alert("learn how to type and comeback.");
}
</script>

How can I use ranges in a switch case statement using JavaScript?

How can I use ranges in a switch case statement using JavaScript? So, instead of writing code for each and every single possibility, I'd like to group them in ranges, For example:
switch(myInterval){
case 0-2:
//doStuffWithFirstRange();
break;
case 3-6:
//doStuffWithSecondRange();
break;
case 6-7:
//doStuffWithThirdRange();
break;
default:
//doStuffWithAllOthers();
}
You have at least four options:
1. List each case
As shown by LightStyle, you can list each case explicitly:
switch(myInterval){
case 0:
case 1:
case 2:
doStuffWithFirstRange();
break;
case 3:
case 4:
case 5:
doStuffWithSecondRange();
break;
case 6:
case 7:
doStuffWithThirdRange();
break;
default:
doStuffWithAllOthers();
}
2. Use if / else if / else
If the ranges are large, that gets unwieldy, so you'd want to do ranges. Note that with if...else if...else if, you don't get to the later ones if an earlier one matches, so you only have to specify the upper bound each time. I'll include the lower bound in /*...*/ for clarity, but normally you would leave it off to avoid introducing a maintenance issue (if you include both boundaries, it's easy to change one and forget to change the other):
if (myInterval < 0) {
// I'm guessing this is an error
}
else if (/* myInterval >= 0 && */ myInterval <= 2){
doStuffWithFirstRange();
}
else if (/* myInterval >= 3 && */ myInterval <= 5) {
doStuffWithSecondRange();
}
else if (/* myInterval >= 6 && */ myInterval <= 7) {
doStuffWithThirdRange();
}
else {
doStuffWithAllOthers();
}
3. Use case with expressions:
JavaScript is unusual in that you can use expressions in the case statement, so we can write the if...else if...else if sequence above as a switch statement:
switch (true){
case myInterval < 0:
// I'm guessing this is an error
break;
case /* myInterval >= 0 && */ myInterval <= 2:
doStuffWithFirstRange();
break;
case /* myInterval >= 3 && */ myInterval <= 5:
doStuffWithSecondRange();
break;
case /* myInterval >= 6 && */ myInterval <= 7:
doStuffWithThirdRange();
break;
default:
doStuffWithAllOthers();
}
I'm not advocating that, but it is an option in JavaScript, and there are times it's useful. The case statements are checked in order against the value you give in the switch. (And again, lower bounds could be omitted in many cases because they would have matched earlier.) Even though the cases are processed in source-code order, the default can appear anywhere (not just at the end) and is only processed if either no cases matched or a case matched and fell through to the default (didn't have a break; it's rare you want to do that, but it happens).
4. Use a dispatch map
If your functions all take the same arguments (and that could be no arguments, or just the same ones), another approach is a dispatch map:
In some setup code:
var dispatcher = {
0: doStuffWithFirstRange,
1: doStuffWithFirstRange,
2: doStuffWithFirstRange,
3: doStuffWithSecondRange,
4: doStuffWithSecondRange,
5: doStuffWithSecondRange,
6: doStuffWithThirdRange,
7: doStuffWithThirdRange
};
Then instead of the switch:
(dispatcher[myInterval] || doStuffWithAllOthers)();
That works by looking up the function to call on the dispatcher map, defaulting to doStuffWithAllOthers if there's no entry for that specific myInterval value using the curiously-powerful || operator, and then calling it.
You can break that into two lines to make it a bit clearer:
var f = dispatcher[myInterval] || doStuffWithAllOthers;
f();
I've used an object for maximum flexibility. You could define dispatcher like this with your specific example:
var dispatcher = [
/* 0-2 */
doStuffWithFirstRange,
doStuffWithFirstRange,
doStuffWithFirstRange,
/* 3-5 */
doStuffWithSecondRange,
doStuffWithSecondRange,
doStuffWithSecondRange,
/* 6-7 */
doStuffWithThirdRange,
doStuffWithThirdRange
];
...but if the values aren't contiguous numbers, it's much clearer to use an object instead.
The ranges in this example are pretty small, but here's how one can handle larger ranges, per the JavaScript MDN Docs:
// The value we'll be evaluating:
let code = 100;
// Matches for any case where the expression === `true`:
switch (true) {
case code <= 64:
return "Your number is 64 or less!";
break;
case code >= 65 && code <= 90:
return "Your number is in the range of 65-90!";
break;
case code >= 97 && code <= 122:
return "Your number is in the range of 97-122!";
break;
case code >= 123:
return "Your number is 123 or greater!";
break;
default:
break;
}
I know that this style was already shown by T.J. Crowder via Use case with Expressions, but I just wanted to show another example of how to utilize this same method. I just did this and had thought maybe another example might help someone, as I was still a little confused after reading other replies.
Is this maybe what you need?
switch(myInterval){
case 0:
case 1:
case 2:
//doStuff();
break;
case 3:
case 4:
case 5:
case 6:
//doStuff();
break;
case 6:
case 7:
//doStuff();
break;
default:
//doStuff();
}
If you know the range is going to be very high(for example 0-100) you can also do this, which is surely easier, cleaner and simpler:
if (myInterval >= 0 && myInterval <= 20) {
//doStuff();
} else if (myInterval > 20 && myInterval <= 60) {
//doStuff();
} else if (myInterval > 60 && myInterval <= 70) {
//doStuff();
} else /* it is greater than 70 */ {
//doStuff();
}
If your ranges are the same and start from 0 you can do some math.
doStuffWithRange(Math.floor(myInterval/range));
For example, if you want RED, GREEN, and BLUE to the map like your example:
Range 0-2 maps to RED
Range 3-6 maps to GREEN
Range 7-8 maps to BLUE
You can write:
function colorInterval(n, max) {
var colors = ["RED", "GREEN", "BLUE"];
var range = max/colors.length
return colors[Math.floor(n/range)];
}
//You get 3 of RED, 3 of GREEN, 2 of BLUE
for (var i=0; i<8; i++) {
console.log(colorInterval(i, 8));
}
Note that the last range in the example is 2, not 3 and this still works as long as the previous ranges are the same.
To add a bit of diversity to the excellent answers already posted, especially as the intervals starts with 0, here is a solution with findIndex (Yeah ES6):
const range = [0, 2, 6, 7];
const randeIndex = range.findIndex(threshold => myInterval <= threshold);
switch (rangeIndex) {
case 1:
//doStuffWithFirstRange();
break;
case 2:
//doStuffWithSecondRange();
break;
case 3:
//doStuffWithThirdRange();
break;
default:
//doStuffWithAllOthers();
}
Because the range array is ordered, findIndex will match the first one. Depending on how you name your ranges, stating from 0 or 1, you may need to remove the first 0 in range.
Use case statement with defined string or value or use "if else if", in case range is higher
int levelNumber = YOUR_VALUE FROM
NSString* strMessage;
switch (levelNumber) {
case 1...10:
{
// Do something...
break;
}
case 11...20:
{
// Do something...
break;
}
case 21...30:
{
// Do something...
break;
}
case 31...40:
{
// Do something...
break;
}
default:
break;
}
Refer:
https://www.codingexplorer.com/loops-switch-statements-ranges-swift/

Categories

Resources