Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript multiple OR conditions in IF statement

Tags:

javascript

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.

like image 909
tempid Avatar asked Feb 03 '12 17:02

tempid


People also ask

Can IF statement have 2 conditions in JavaScript?

You can use the logical AND (&&) and logical OR (||) operators to specify multiple conditions in an if statement. When using logical AND (&&), all conditions have to be met for the if block to run.

Can you have 3 conditions in an if statement JavaScript?

Using either “&&” or “||” i.e. logical AND or logical OR operator or combination of can achieve 3 conditions in if statement JavaScript.

How do you write multiple if conditions in JavaScript?

We can also write multiple conditions inside a single if statement with the help of the logical operators && and | | . The && operators will evaluate if one condition AND another is true. Both must be true before the code in the code block will execute.

Can IF statement have 2 conditions?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.


2 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.

like image 75
Gabe Avatar answered Sep 22 '22 01:09

Gabe


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]))
like image 36
Mike Samuel Avatar answered Sep 24 '22 01:09

Mike Samuel