How to use the OR clause in a JavaScript IF statement?

I understand that in JavaScript you can write:

if (A && B) { do something } 

But how can I implement OR, for example:

 if (A OR B) { do something } 
+101
javascript if-statement
Mar 02
source share
10 answers

Just use the doublepipe operator, which || .

 if (A || B) 
+230
Mar 02
source share

It is worth noting that || will also return true if BOTH A and B are true .

In JavaScript, if you are looking for A or B , but not both, you need to do something similar to:

 if( (A && !B) || (B && !A) ) { ... } 
+78
Mar 02 '10 at 14:50
source share
+16
Mar 02
source share
 if (A || B) { do something } 
+14
Mar 02
source share

|| is an or operator.

 if(A || B){ do something } 
+12
Mar 02 '10 at 14:40
source share

here is my example:

 if(userAnswer==="Yes"||"yes"||"YeS"){ console.log("Too Bad!"); } 

This suggests that if the answer is yes or YeS, then the same thing will happen.

+9
Dec 30 '15 at 20:41
source share

Just use ||

 if (A || B) { your action here } 

Note: string and number. This is harder.

Check this one for a deeper understanding:

0
Jun 27 '14 at 16:02
source share

To use the OR(||) operator if the condition and notation is || More than one condition statement is required. ,

 if(condition || condition){ some stuff } 
0
Apr 25 '17 at 4:21 on
source share

You can use as

 if(condition1 || condition2 || condition3 || ..........) { enter code here } 
0
Jan 29 '19 at 17:54
source share
 if (/A|B/.test(thingToTest)) { doSomething } 

example:

  var myString = "This is my search subject" if (/my/.test(myString)) { doSomethingHere } 

This will look for "my" in the variable "myString". You can replace the string directly instead of the variable "myString".

As an added bonus, you can add to the search case insensitive "i" and global "g".

  var myString = "This is my search subject" if (/my/ig.test(myString)) { doSomethingHere } 
0
Mar 21 '19 at 12:31 on
source share



All Articles