I think I'm missing something basic here. Why is the third IF condition true? Shouldn't the condition evaluate to false? I want to do something where the id is not 1, 2 or 3.

var id = 1; if(id == 1) //true if(id != 1) //false if(id != 1 || id != 2 || id != 3) //this returns true. why? 

Thank you.

7

6 Answers

With an OR (||) operation, if any one of the conditions are true, the result is true.

I think you want an AND (&&) operation here.

4

You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say

the id is not 1, and the id is not 2, and the id is not 3.

which translates to

if (id !== 1 && id !== 2 && id !== 3) 

or alternatively for something more pythonesque:

if (!(id in [,1,2,3])) 
4

Each of the three conditions is evaluated independently[1]:

id != 1 // false id != 2 // true id != 3 // true 

Then it evaluates false || true || true, which is true (a || b is true if either a or b is true). I think you want

id != 1 && id != 2 && id != 3 

which is only true if the ID is not 1 AND it's not 2 AND it's not 3.

[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.

When it checks id!=2 it returns true and stops further checking

1

because the OR operator will return true if any one of the conditions is true, and in your code there are two conditions that are true.

This is an example:

false && true || true // returns true false && (true || true) // returns false (true || true || true) // returns true false || true // returns true true || false // returns true 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy