I'm running two seemingly identical statements to check whether a number is positive, negative or zero.
The if
statement returns the expected result.
The switch
statement always returns the default.
Why?
In this example I pass "2
" (type: number
) and I get +
in the if
statement and ?
in the switch
statement.
// Verify whether a number is positive, negative or Zero:
function myFuncIf(y) {
let result = null;
console.log("y is " + y);
console.log("y is " + typeof(y));
if (y > 0) {
return "+";
} else if (y < 0) {
return "-";
} else {
return "?";
}
}
function myFuncSwitch(y) {
let result = null;
console.log("y is " + y);
console.log("y is " + typeof(y));
switch (y) {
case (y > 0):
result = "+";
break;
case (y < 0):
result = "-";
break;
default:
result = "?";
}
return result;
}
console.log(myFuncIf(2));
console.log(myFuncSwitch(2));