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.
I know I could save all the values in variables and check those subsequentlyYou already know the answer, unfortunately it's not very pretty as you state.returnstatement imply that you want to know whether all checks returntrue? Then you also don’t need to evaluate all the checks… If you want to get the result of each check individually, then use the suggestion with the array literal from A.Wolff.checkSomethinghandles two separate tasks at the same time which is generally bad practice and leads to problems like this. Depending on what the actual use case is, ifdoSomethinghas to run twice you should do that task separately instead of relying on it being a consistent side effect ofcheckSomething.falsevalue, the overall result of three&&operations can never betrueso why execute them? Unless you have side effects in those parts of the expression (which is an evil way to code). Fix your code rather than code this way.