eclipseIzHere
eclipseIzHere

Reputation: 83

Switch statement not behaving like it should

so i have a piece of code where i have an array (ar=[1,2,3,4,5]) and two functions. the functions are supposed to do the exact same thing: print out something if 1 exists in the array. but function func is always returning "nope" instead of "one" but function another always return the right thing. the only difference between the two functions is function func have a switch instead of an if/else. why? in the source code there are about 12 cases so i actually need to use the switch.

var ar=[1,2,3,4,5];
function func(num){
    var one=num;
    switch (one) {
        case one===1:
            console.log("one");
            break;
        default:
            console.log("nope");
            break;
    }
}
function another (num) {
     if(num===2){
        console.log("found two");
     } else if(num===3){
        console.log("found thre");
     } else{
        console.log("nope");
     }
}

ar.forEach(func);
ar.forEach(another);

Upvotes: 0

Views: 41

Answers (2)

Tyr
Tyr

Reputation: 2810

Easiest way. Change the switch param to true if you want to use a comparison in the case, because one===1 returns true/false. This is why you always get "nope".

var ar=[1,2,3,4,5];
function func(num){
    var one=num;
    switch (true) {
        case one===1:
            console.log("one");
            break;
        default:
            console.log("nope");
            break;
    }
}

Upvotes: 0

Seif Sayed
Seif Sayed

Reputation: 803

You have to use the value you want to compare to one

hence

case 1:

instead of

case one===1

here's a fiddle https://jsfiddle.net/cunx1ono/

Upvotes: 3

Related Questions