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 }
Use the logical "OR" operator, that is ||.
if (A || B)
Note that if you use string comparisons in the conditions, you need to perform a comparison for each condition:
if ( var1 == "A" || var1 == "B" )
If you only do it in the first one, then it will always return true:
if ( var1 == "A" || "B" ) //don't do this; it is equivalent to if ("B"), which is always true
The official ECMAScript documentation can be found here
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) ) { ... }
if (A || B) { do something }
Use the || operator.
|| 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
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");
You may also want to filter an IF statement when condition1 equals 'something' AND condition2 equals 'another thing' OR 'something else'. You can do this by placing condition2 in another set of brackets eg...
if (condition1 === 'x' && (condition2 === 'y' || condition2 === 'z')) {
console.log('do whatever')
}
If condition2 is NOT in it's own brackets then condition1 has to be x AND condition2 has to be y for the function to trigger...
... but it will also trigger if condition2 is z, regardless of what condition1 is. Which may be okay depending on your use case, but something to be mindful of.
Related
I want to write an if/else statement that tests if the value of a text input does NOT equal either one of two different values. Like this (excuse my pseudo-English code):
var test = $("#test").val();
if (test does not equal A or B){
do stuff;
}
else {
do other stuff;
}
How do I write the condition for the if statement on line 2?
Think of ! (negation operator) as "not", || (boolean-or operator) as "or" and && (boolean-and operator) as "and". See Operators and Operator Precedence.
Thus:
if(!(a || b)) {
// means neither a nor b
}
However, using De Morgan's Law, it could be written as:
if(!a && !b) {
// is not a and is not b
}
a and b above can be any expression (such as test == 'B' or whatever it needs to be).
Once again, if test == 'A' and test == 'B', are the expressions, note the expansion of the 1st form:
// if(!(a || b))
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')
ECMA2016 answer, especially good when checking against multiple values:
if (!["A","B", ...].includes(test)) {}
In general it would be something like this:
if(test != "A" && test != "B")
You should probably read up on JavaScript logical operators.
I do that using jQuery
if ( 0 > $.inArray( test, [a,b] ) ) { ... }
For a larger number of values that is checked against often, it may be more efficient to check if the value does not exist in a Set.
const values = new Set(["a", "b"]);
if(!values.has(someValue)){
// do something
} else {
// do something else
}
var test = $("#test").val();
if (test != 'A' && test != 'B'){
do stuff;
}
else {
do other stuff;
}
You used the word "or" in your pseudo code, but based on your first sentence, I think you mean and. There was some confusion about this because that is not how people usually speak.
You want:
var test = $("#test").val();
if (test !== 'A' && test !== 'B'){
do stuff;
}
else {
do other stuff;
}
This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).
switch(test) {
case A:
case B:
do other stuff;
break;
default:
do stuff;
}
Using the traditional if statement I can do this:
if(a===0 || b===0) {console.log('aloha amigo')};
But when I try to do something the same thing with a ternary operator, like this:
a===0 || b===0 && console.log('aloha amigo')
I just get errors about unexpected ||.
According to this answer: Precedence: Logical or vs. Ternary operator, we can do it using
condition1 || condition2 ? do if true : do if false
(Sorry I'm not sure how to call the ? : symbols in this case), but I'm not sure how to get it running using && (It means only run the code if returned true).
I created a codepen to test it easily. Here's the whole code:
var a = 0;
var b = 1;
a===0 || b===0 ? console.log('Works here') : console.log('And here');
a===0 || b===0 && console.log('Doesn\'t work here');
a===0 && console.log('The && works for a single test');
Here's the link
Just take parenthesis to prevent operator precedence of && over ||
(a === 0 || b === 0) && console.log('aloha amigo')
Without parenthesis, you get (now with to show the precedence) a different result.
a === 0 || (b === 0 && console.log('aloha amigo'))
^^^^^^^ first evaluation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ second evaluation
I'm writing a script to be executed when my body element hasn't got any of the following classes:
a OR b OR c AND d
I tried this, but it doesn't seem to do the trick:
if ((!$('body').hasClass('a')) || (!$('body').hasClass('b')) || ((!($('body').hasClass('c')) && (!$('body').hasClass('d'))))) {
}
UPDATE
This seems to work:
if (!($('body').hasClass('a') || $('body').hasClass('b') || $('body').hasClass('c') && $('body').hasClass('d'))) {
}
use
$(function(){
if ((!$('body').hasClass('a')) || (!$('body').hasClass('b')) || !($('body').hasClass('c') && $('body').hasClass('d'))) {
}
});
You are looking for a body that doesnt have any of the classes, so you need to use &&. Heres what happens:
if(hasclass(a) || hasclass(b)) = if(true OR false) = if(true)
Above the OR operator || means that once it hits a true evaluation, it will execute your if-block.
if(hasclass(a) && hasclass(b)) = if(true AND false) = if(false)
Here the AND operator && means that once you hit a false evaluation, you block won't be executed.
You want the last thing to happen, since you want it to have neither of the classes. Learn how to play with these operators as they can be very confusing. As long as you remember that the AND operator will execute only if all statements are true and the OR operator will only execute if one of the statements is true. Nested operators work the same, so if((a = b && b = c) || (a = c)) will execute if a,b and c are the same OR when a and c are the same, but not when a and b are the same or a and c are the same.
More on expression and operators (specifically Bitwise and a must read): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators
If i want to test two properties of one in javascript i have to write
((a test b ) && (a test c))
is there a way to write something like
(a test ( b && c))
for example
if(a === NaN || a === Infinity){…}
to
if (a === (NaN || Infinity)){…}
Just wondering if there were shorthands like this.
Sadly, no.
if (a === (NaN || Infinity)){…} would test a === Infinity. First it would check (NaN || Infinity) (evaluates to Infitity), the check.
Additionally, checking against NaN always returns false. Try it: NaN === NaN. Use isNaN(a) instead.
Yes, there is a shortcut:
if ([val1, val2, val3 /*...*/].indexOf(a) > -1){ /* ... */ }
or even shorter:
if (~[val1, val2, val3 /*...*/].indexOf(a)){ /* ... */ }
Note it won't work with NaN, because comparing to NaN is useless. Even NaN == NaN is false, that's why there are isNaN and Number.isNaN.
The law of non-contradiction dictates that two contradictory statements cannot both be true at the same time. That means that the expressions
(a && !a)
(a == !a)
(a === !a)
should always evaluate to a falsy value, and
(a || !a)
should always evaluate to a truthy value.
Fortunately, though, Javascript is a fun language that allows you to do all sorts of sick things. I bet someone a small fortune that it's possible to convince Javascript to break the law of non-contradiction, or, at least, convincingly make it look like it's breaking the law of non-contradiction. Now I'm trying to make all four of the above code examples give the unexpected result.
What would be a good way to go about this?
The best I can do is:
[] == ![] // true
or
var a = [];
a == !a
Of course this is really doing [] == false // true and !![] == ![] // false. It's really just a technicality.
EDIT: This is really a joke, but does work:
var a = false; var b = function() { return a = !a };
console.log(!!(b() && !b())); // true
console.log(b() == !b()); // true
console.log(b() === !b()); // true
console.log(b() || !b()); // true
This one will do the trick:
var a = '0';
a == !a
(evaluates to true)
In this case, a == false and !a == false.
a=NaN;
var a=NaN,
A=[(a && !a), (a == !a),(a === !a),(a || !a)];
alert(A)
/* returned value: (Array)
NaN,false,false,true
*/
I still haven't found anything to break && and ===, but here's one for == and ||:
Object.prototype.toString = function() {
return false;
};
a = {};
b = (a || !a);
alert(a || !a); //alerts false
alert(b == !b); //alerts true