0

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
Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115
Bijay Timilsina
  • 757
  • 2
  • 10
  • 25

2 Answers2

1

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, "A is either 1 or 2". That's not the way the OR is 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.

Joe
  • 1,091
  • 1
  • 11
  • 23
0

You gotta make your two conditions separately with || as follow: a[i] === "king" || a[i] === "queen"

Basim Hennawi
  • 2,651
  • 3
  • 19
  • 31