Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid short-circuited evaluation in JavaScript?

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.

like image 321
Duncan Luk Avatar asked Jan 30 '16 11:01

Duncan Luk


People also ask

Does JavaScript have short-circuit evaluation?

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.

Does JavaScript use lazy evaluation?

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.

What is the use of || in JavaScript?

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.

What are the advantages about short-circuit evaluation?

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.


2 Answers

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)
 }
like image 140
brewsky Avatar answered Oct 16 '22 16:10

brewsky


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);
}
like image 24
Nina Scholz Avatar answered Oct 16 '22 15:10

Nina Scholz