Reputation: 396
I'm having a problem using a mathematical operator in a switch expression.
This is what my code currently looks like:
var x = 18;
var y = 82;
var result = x + y;
switch(result) {
case "200":
document.write("200!");
break;
case "500":
document.write("500!");
break;
case "100":
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}
Explained: the variable "result" has a value of 100. I am trying to use that value with the switch operator, but it just isn't working.
I've also tried using the equation itself as the switch expression, but that doesn't work either.
P.S: I just started out with JavaScript. Bet I missed something obvious...
Upvotes: 3
Views: 2623
Reputation: 120268
Change "100" to 100 and it works. switch must be using the semantics of ===
which means 'type and value are equal' vs ==
, which will try to make the types similar and then compare.
EDIT -- here is a screenshot showing it working
Upvotes: 5
Reputation:
You are using strings in your case statements. Take the quotes ("
) out and you should be fine.
Upvotes: 3
Reputation: 45578
You're comparing the number 100
to the string "100"
, that isn't the same. Try this:
var x = 18;
var y = 82;
var result = x + y;
switch(result) {
case 200:
document.write("200!");
break;
case 500:
document.write("500!");
break;
case 100:
document.write("100! :)");
break;
default:
document.write("Something's not right..");
}
Upvotes: 4