The logical AND &&
operator returns:
- The first falsy value, or;
- The last operand if no falsy value exists.
In the following examples you can see how the first falsy value is returned:
console.log(false && true); // false console.log([].length && true); // 0 console.log(0 && true); // 0 console.log(NaN && true); // NaN console.log('' && true); // '' console.log(null && true); // null console.log(undefined && true); // undefined // ...
This happens because the expression is evaluated from left-to-right, and wherever a falsy value is encountered, the whole expression short-circuit evaluates to false
. This means that it does not matter where in the expression the falsy value resides; the first operand that evaluates to false
will be returned.
In the following examples you can see how the last operand is returned when the expression evaluates to true
:
console.log(true && 'foo'); // 'foo' console.log(true && 1); // 1 console.log(true && [1, 2, 3].length); // 3 console.log(true && true); // true // ...
If you wish to always return a boolean value, you can simply convert the result of the logical AND expression to boolean.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.