How to avoid a short-circuited assessment in JavaScript?

I need to execute both sides of the && instruction, but this will not happen if the first part returns false . Example:

 function checkSomething(x) { var not1 = x !== 1; if (not1) doSomething(x); return not1; } function checkAll() { return checkSomething(1) && checkSomething(3) && checkSomething(6) } var result = checkAll(); 

The problem is that doSomething(x) needs to be executed twice, but since checkSomething(1) returns false , no other checks will be called. What is the easiest way to run all checks and return the result?

I know that I can save all the values ​​in variables and check them afterwards, but this does not look very clean when I have a lot of checks. I am looking for alternatives.

+5
source share
2 answers

You can multiply the result of the comparison and translate it into 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); } 
+5
source

Use single &. This is a bitwise operator. He will fulfill all the conditions and then return a bitwise sum of the results.

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

Source: https://habr.com/ru/post/1241878/


All Articles