How to use OR condition in a JavaScript IF statement?
JavascriptBoolean ExpressionJavascript Problem Overview
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 }
Javascript Solutions
Solution 1 - Javascript
Simply use the logical "OR" operator, that is ||
.
if (A || B)
Solution 2 - Javascript
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) ) { ... }
Solution 3 - Javascript
Solution 4 - Javascript
if (A || B) { do something }
Solution 5 - Javascript
||
is the or operator.
if(A || B){ do something }
Solution 6 - Javascript
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
Solution 7 - Javascript
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");
Solution 8 - Javascript
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 + '.');
}
Solution 9 - Javascript
More then one condition statement is needed to use OR(||)
operator in if conditions and notation is ||
.
if(condition || condition){
some stuff
}
Solution 10 - Javascript
You can use Like
if(condition1 || condition2 || condition3 || ..........)
{
enter code here
}
Solution 11 - Javascript
Just use ||
if (A || B) { your action here }
Note: with string and number. It's more complicated.
Check this for deep understading: