samedi 30 janvier 2016

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 checkSomething(x) {
    var not1 = x !== 1;
    if (not1) doSomething();

    return not1;
}

function checkAll() {
    return checkSomething(1)
        && checkSomething(2)
        && checkSomething(3)
}

checkAll();

The problem here is that doSomething() should be executed twice, 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, so I am looking for alternatives.

Aucun commentaire:

Enregistrer un commentaire