ankush981
ankush981

Reputation: 5417

Understanding expressions inside switch

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

Answers (3)

Sanjeev Hegde
Sanjeev Hegde

Reputation: 168

(X+1)==2 returns true not 1. Use value inside case.

Upvotes: 0

risto
risto

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

Verhaeren
Verhaeren

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

Related Questions