eclipseIzHere eclipseIzHere - 3 months ago 6
Javascript Question

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

Tyr Tyr
Answer

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