Bijay Timilsina Bijay Timilsina - 21 days ago 8
Javascript Question

Weird if-else behaviour Javascript

The else-statement below never executes even if the if-statement is false. I think I've made some very basic mistake but can't figure out what.

var a = ["king","queen","100"];
for (var i=0; i<a.length; i++) {
if (a[i] === "king" || "queen"){
console.log("monarch");
}
else {
console.log("The number is: "+ parseInt(a[i]));
}
}
// This prints out "monarch" 3 times

Joe Joe
Answer

should be:

var a = ["king","queen","100"];
    for (var i=0; i<a.length; i++) {
        if (a[i] === "king" || a[i] ===  "queen"){
            console.log("monarch");
        }
        else {
            console.log("The number is: "+ parseInt(a[i]));
        }
    }

You wrote your boolean expression the way we would speak a spoken language, "either A is 1 or 2". That's not the way OR's are interpreted.

Either the Left side of the OR is TRUE... a[i] === "king" is TRUE... or the Right side of the OR is TRUE... "queen". It's evaluating the string by itself, and the string "queen" is not null, so it evaluates to TRUE.

Comments