I need to execute both sides of an &&
statement, but this won't happen if the first part returns false
. Example:
function doSomething(x) {
console.log(x);
}
function checkSomething(x) {
var not1 = x !== 1;
if (not1) doSomething(x);
return not1;
}
function checkAll() {
return checkSomething(1)
&& checkSomething(3)
&& checkSomething(6)
}
var allValid = checkAll(); // Logs nothing, returns false
The problem here is that doSomething(x)
should log 3 and 6, but because checkSomething(1)
returns false
, the other checks won't be called. What is the easiest way to run all the checks and return the result?
I know I could save all the values in variables and check those subsequently, but that does not look very clean when I have a lot of checks. I am looking for alternatives.
In JavaScript short-circuiting, an expression is evaluated from left to right until it is confirmed that the result of the remaining conditions is not going to affect the already evaluated result.
One of the reasons often cited is lazy evaluation. Javascript has the fame of being functional, but it lacks a native way to do most of the stuff commonly considered as such. Again, one of those is lazy evaluation.
The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value.
The advantages of C#'s short-circuit evaluation. There are two benefits to the short-circuit behaviour of the && and || operators. It makes our true/false conditions more efficient since not every expression has to be evaluated. And short-circuiting can even prevent errors because it skips part of the code.
Use a single &. That is a bitwise operator. It will execute all conditions and then return a bitwise sum of the results.
function checkAll() {
return checkSomething(1)
& checkSomething(2)
& checkSomething(3)
}
You can multiply the comparison result and cast it to boolean.
function checkSomething(x) {
var not1 = x !== 1;
if (not1) alert(x);
return not1;
}
function checkAll() {
return !!(checkSomething(1) * checkSomething(2) * checkSomething(3));
}
document.write(checkAll());
Or take some array method:
function checkAll() {
return [checkSomething(2), checkSomething(2), checkSomething(3)].every(Boolean);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With