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.
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:
With an
OR
(||) operation, if any one of the conditions are true, the result is true.I think you want an
AND
(&&) operation here.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
which translates to
or alternatively for something more pythonesque:
When it checks id!=2 it returns true and stops further checking
Each of the three conditions is evaluated independently[1]:
Then it evaluates
false || true || true
, which is true (a || b
is true if eithera
orb
is true). I think you wantwhich 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.