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 }
This question is related to
javascript
boolean-expression
Simply use the logical "OR" operator, that is ||
.
if (A || B)
One can use regular expressions, too:
var thingToTest = "B";_x000D_
if (/A|B/.test(thingToTest)) alert("Do something!")
_x000D_
Here's an example of regular expressions in general:
var myString = "This is my search subject"_x000D_
if (/my/.test(myString)) alert("Do something here!")
_x000D_
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"_x000D_
if (/my/ig.test(myString)) alert("Do something here");
_x000D_
||
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
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) ) { ... }
More then one condition statement is needed to use OR(||)
operator in if conditions and notation is ||
.
if(condition || condition){
some stuff
}
Just use ||
if (A || B) { your action here }
Note: with string and number. It's more complicated.
Check this for deep understading:
if (A || B) { do something }
You can use Like
if(condition1 || condition2 || condition3 || ..........)
{
enter code here
}
If we're going to mention regular expressions, we might as well mention the switch
statement.
var expr = 'Papayas';_x000D_
switch (expr) {_x000D_
case 'Oranges':_x000D_
console.log('Oranges are $0.59 a pound.');_x000D_
break;_x000D_
case 'Mangoes':_x000D_
case 'Papayas': // Mangoes or papayas_x000D_
console.log('Mangoes and papayas are $2.79 a pound.');_x000D_
// expected output: "Mangoes and papayas are $2.79 a pound."_x000D_
break;_x000D_
default:_x000D_
console.log('Sorry, we are out of ' + expr + '.');_x000D_
}
_x000D_
Source: Stackoverflow.com