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 }
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 }
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) ) { ... }
(Math.pow(2,32)-1) ^ 0; // -1 (success)
... Math.pow(2,32) ^ 0; // 0 (failure)
if (A ? !B : B) {...
would be a shorter substitute that wouldn't have the 32-bit limitation. Or maybe if (!A != !B) {...
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
if (name === 'Jam' || name === 'Jem' || name == 'Jum')
if (number === 1||2||3)
is like while (true)
; the second and third conditions ask if 2 is 2 and/or 3 is 3. They always resolve as true to the statement always passes. There goes my plan to reduce the character count. Keeping the statements in parenthesis does make it easier to read though.
Jul 13, 2015 at 15:03
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");
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
}
You can use Like
if(condition1 || condition2 || condition3 || ..........)
{
enter code here
}
Just use ||
if (A || B) { your action here }
Note: with string and number. It's more complicated.
Check this for deep understading: