Reputation: 5417
Consider the following script:
var x = 1;
switch (x) {
case ( ( x+1 ) == 2 ):
console.log("It works!");
break;
default:
console.log("Nope, not happening.");
break;
}
Now, I've read that expressions inside case
are evaluated and then compared to the variable. Here, since x
is 1, ( x+1 ) == 2
evaluates to TRUE
. Also, the value of x
(which is 1, originally) in equivalent to TRUE
. If this reasoning is correct, why am I getting the message "Nope, not happening"?
Please explain.
Upvotes: 0
Views: 41
Reputation: 1304
You didn't read the signature of the switch
statement properly. It switch (x)
asks for an expression x
, while case y
asks for a value y
.
See my fiddle and the documentation.
Upvotes: 1
Reputation: 1661
Do it this way:
var x = 1;
switch (x + 1) {
case 2:
console.log("It works!");
break;
default:
console.log("Nope, not happening.");
break;
}
Upvotes: 2