What Is Returned by "&&" in JavaScript?

The logical AND && operator returns:

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.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.