The && operator is known as "boolean AND ". Typically, you will see it in the if :
if (x == true && y == false) {
but this is not a limitation. You can use it in any real expression to "combine" the logical values โโof your operands into one logical result in accordance with the logical "AND":
var z = (x == true && y == false); // z is now true or false, accordingly
One of the great things about && is that it is short circuits. In false && true , since the first operand is false , the whole expression can only be evaluated to false , so the second operand is not even evaluated.
Repeat one more time:
var z = (false && foo()); // z is now false
In this statement, the function foo never called! It is not necessary for the program to know that z will be false.
This is more than optimization - you can rely on it.
Some stupid people use this technique to rewrite conditional statements:
if (x == 0) { foo(); }
into hard-to-read single expressions:
(x == 0) && foo();
Now consider that an assignment can be an expression similar to a function call:
var a = (b = c);
Or:
var a = (b = foo());
And add the conditional value using the above method:
var a = ((x == 0) && (b = foo()));
Now the whole expression b = foo() will not be evaluated at all if x not 0 due to a short circuit.
We do not need to do anything with the result of the && operation, and if we do not store it on a , you will remain with:
(x == 0) && (b = foo());
which is an operator that assigns b to foo() only if x is 0 .
Avoid this. Hard to read. Just use the if .