Why does javascript ignore the execution of certain line under certain conditions?

Viewed 55

Today I noticed that JavaScript ignores the execution of certain line under certain conditions.

For example, a normal person would read the following code and think that value is false should be logged 5 times.

const values = [false, false, false, false, false];

const isTrue = (value) => {
  console.log(`value is ${value}`);
  return !!value;
};

let isAllTrue = true;

values.forEach(value => {
  isAllTrue &&= isTrue(value);
});

However, this code logged it once.
This code shows that once isAllTrue is false, isAllTrue will never be true due to &&= no matter what you do. This is why I thought that function executions were being ignored. And I thought this was an optimization by JavaScript.

I wanted to know the exact reason, so I googled, but I couldn't find the specification. If you know where the specifications are, please let me know.

2 Answers

You're witnessing short-circuit evaluation.

First, let's unwrap isAllTrue &&= isTrue(value) to make it a bit clearer. If we write this statement in its longer form, it will be isAllTrue = isAllTrue && isTrue(value).

After the first iteration, isAllTrue will be false, so no matter what isTrue(value) will return, the result of isAllTrue && isTrue(value) will always be false. Since the result is known without evaluating isTrue(value), JavaScript optimizes it away and doesn't even call it.

From the docs of && - LOGICAL AND :

The logical AND (&&) operator (logical conjunction) for a set of Boolean operands will be true if and only if all the operands are true. Otherwise it will be false.

More generally, the operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.

Which basically means if the first expression before && is false. The second is never even reached. This is no optimization by JS. This is how the operator works in coding languages. That is exactly what is happening to your code. The function is only run once. Once the value of isAllTrue is false. It never becomes true again

Related