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
5
  • 2
    "queen" is a truthy value. Do this a[i] === "king" || a[i] === "queen" Commented Nov 13, 2016 at 14:15
  • thanks it worked but shouldn't both king and queen be false for a[2] Commented Nov 13, 2016 at 14:17
  • Yes a[2] === "king" || a[2] === "queen" is false. Commented Nov 13, 2016 at 14:19
  • you do not need parseInt(a[i]), because you add a string to the string. Commented Nov 13, 2016 at 14:19
  • 1
    Take note, when you say a[i] === "king" || "queen" you are asking if a[i] equals to "king", and after you ask another question, literaly "queen", but you want to ask a[i]==="queen". so your conditional should be like @OriDrori says Commented Nov 13, 2016 at 14:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

so you mean the way javascript checks the condition is : either a[i]="king" or "queen" in which case for a[2] the if a[2]="king" is false but if the lone ("queen") is still correct right?
@BijayTimilsina exactly!
@TiagoMarinho - nice edits, thanks for the additional clarification.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.