Inequalities inside a switch statement [duplicate] - javascript

This question already has answers here:
JavaScript conditional switch statement
(5 answers)
Closed 7 years ago.
I just started learning about the switch command in JavaScript, and was wondering if the cases could be constructed so as to include inequalities (<, >, <= and >=), instead of equality (==). Also, can one control whether it is a strict equality (===) or not? The following code does not even bring up a prompt, so I'm not sure if I've coded correctly:
var a = prompt("Please input a number.");
switch (a) {
case { < 1 }:
alert("less than 1");
break;
case { < 2 }:
alert("less than 2");
break;
case { < 3 }:
alert("less than 3");
break;
default:
alert("greater than or equal to 3");
}

It is actually possible, if you do it like this. The case whose expression evaluates to true is executed.
var a = +prompt("Please input a number.");
switch (true) {
case (a<1): alert("less than 1");
break;
case (a<2): alert("less than 2");
break;
case (a<3): alert("less than 3");
break;
default: alert("greater than or equal to 3");
}
Note: Personally I feel you should use if-else for this purpose.

Related

Switch statement is not taking the input [duplicate]

This question already has answers here:
Switch Statement, it does not work with prompt
(3 answers)
Closed 1 year ago.
What is wrong with this code? The switch statement is not taking the input. If I declare the value of variable 'a' directly then it is showing the output.
var a = prompt("value");
console.log(fun(a));
function fun(value)
{
let ans = "";
switch(value)
{
case 1:
ans = "alpha";
break;
case 2:
ans = "beta";
break;
case 3:
ans = "gamma";
break;
}
return ans;
}
You are comparing integers with string, just add quotes to cases
var a = prompt("value");
console.log(fun(a));
function fun(value)
{
let ans = "";
switch(value)
{
case "1":
ans = "alpha";
break;
case "2":
ans = "beta";
break;
case "3":
ans = "gamma";
break;
}
return ans;
}
Switch uses strict equality (===) to match Switch expression to case clauses.
In your code, value is a string but your case clauses are numbers, so because of strict equality, string value won't be coerced to match the case clauses which are numbers.
You can convert the result of prompt to a number before passing it to the function.
Change
var a = prompt("value");
to
var a = Number(prompt("value"));

JS: Why don't the switch statement cases `case 2` and `case day == 2` print out the same result?

I understand the following code.
var day = 2;
switch (day) {
case 1:
document.write("Monday");
break;
case 2:
document.write("Tuesday!!");
break;
case 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
It prints out "Tuesday!!".
However, why doesn't the following work? I though it should have printed the same answer, but it keeps printing "Another Day"!?
var day = 2;
switch (day) {
case day == 1:
document.write("Monday");
break;
case day == 2:
document.write("Tuesday!!");
break;
case day == 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
A case in a switch statement tries to match with the switch condition directly. So your snippet:
var day = 2;
switch (day) {
case day == 1:
document.write("Monday");
break;
case day == 2:
document.write("Tuesday!!");
break;
case day == 3:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
Is actually equivalent to:
var day = 2;
switch (day) {
case false:
document.write("Monday");
break;
case true:
document.write("Tuesday!!");
break;
case false:
document.write("Wednesday");
break;
default:
document.write("Another day");
}
And since day is not equal to either true or false (since it is, in fact, 2), the switch falls through to its default case.
You can see that cases use strict equality from the docs (emphasis mine):
A switch statement first evaluates its expression. It then looks for
the first case clause whose expression evaluates to the same value as
the result of the input expression (using strict comparison, ===) and
transfers control to that clause, executing the associated statements.
It's because switch case statements compare the supplied arguments automatically. So on calling day == 3, it's actually running day == 3 == 3 which isn't a correct syntax.
Hope it clear your doubts.

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.

switch statement to compare values greater or less than a number

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;
}

javascript switch/case : are types compared? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is it safe to assume strict comparison in a Javascript switch statement?
Does a switch/case statement in javascript compare types or only values?
In other words, when I have the following code:
switch (variable)
{
case "0": [...] break;
case "1": [...] break;
default: [...] break;
}
is it equivalent to
if ( variable == "0" )
{
[...]
}
else if ( variable == "1" )
{
[...]
}
else
{
[...]
}
or to
if ( variable === "0" )
{
[...]
}
else if ( variable === "1" )
{
[...]
}
else
{
[...]
}
edit: is there a way to force compare values and types at once?
Yes, types are compared.
If input is equal to clauseSelector as defined by the === operator,
then set found to true.
ECMA-262, page 95.
It checks types as well,
Example:
var x = false;
switch (x) {
case "":
alert('x'); /// Not happening
break;
case false:
alert('y'); // happen
break;
}​
Live DEMO
And as the spec says:
If input is equal to clauseSelector as defined by the === operator, then...

Categories

Resources