Conditionals Question

Hi, I am reading the Making decisions in your code — conditionals section.


There’s a particular “what not to do” example that was explained but I’m still not 100% clear on why it returns True, no matter what.


if (x === 5 || 7 || 10 || 20) {
  // run my code
}

I tested the example for learning purposes, i.e.

Screenshot 2023-10-09 at 6.35.13 PM


I know the correct way to write this, just needing more clarity on the above. Any help is appreciated, thank you!

Hello, jt_1. I’m not affiliated with Mozilla; I’m going through their Web development course as well. But this is a question I can answer.

Each expression between the OR operators is its own Boolean sub-expression. The 7, 10, and 20 have no connection to the first expression (x === 5); they are completely separate from it, and each other. Given that x = 2, the first sub-expression is evaluated first. Since it comes out false, it goes on to the next one, which is 7. This is a non-Boolean number being evaluated in a Boolean context. According to the article you linked to, “Any value that is not false , undefined , null , 0 , NaN , or an empty string ( '' ) actually returns true when tested as a conditional statement.” The 7, therefore, evaluates as true. At this point, JavaScript knows that the full expression evaluates to true; therefore, it doesn’t bother to evaluate the other two sub-expressions (a behavior called “short-circuiting”). So it always evaluates to true regardless of the value of x.

I hope this is clear enough to be helpful.