How to Use or Condition in a Javascript If Statement?

I understand that in JavaScript you can write:

if (A && B) { do something }

But how do I implement an OR such as:

if (A OR B) { do something }
5

Simply use the logical "OR" operator, that is ||.

if (A || B)
2

Worth noting that || will also return true if BOTH A and B are true.

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

if( (A && !B) || (B && !A) ) { ... }
6
if (A || B) { do something }

|| is the or operator.

if(A || B){ do something }

here is my example:

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

This says that if the answer is Yes yes or YeS than the same thing will happen

5

One can use regular expressions, too:

var thingToTest = "B";
if (/A|B/.test(thingToTest)) alert("Do something!")

Here's an example of regular expressions in general:

var myString = "This is my search subject"
if (/my/.test(myString)) alert("Do something here!")

This will look for "my" within the variable "myString". You can substitute a string directly in place of the "myString" variable.

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

var myString = "This is my search subject"
if (/my/ig.test(myString)) alert("Do something here");
1

If we're going to mention regular expressions, we might as well mention the switch statement.

var expr = 'Papayas';
switch (expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas': // Mangoes or papayas
    console.log('Mangoes and papayas are $2.79 a pound.');
    // expected output: "Mangoes and papayas are $2.79 a pound."
    break;
  default:
    console.log('Sorry, we are out of ' + expr + '.');
}

More then one condition statement is needed to use OR(||) operator in if conditions and notation is ||.

if(condition || condition){ 
   some stuff
}
1

You can use Like

if(condition1 || condition2 || condition3 || ..........)
{       
     enter code here
}
1

Just use ||

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

Note: with string and number. It's more complicated.

Check this for deep understading:

2
Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest