Why Is JavaScript "&&" Returning a Non-Boolean Value?

Find out about the return value of logical and operator

The logical AND && operator actually 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
// ...

In case, you want to always return a boolean value, you can use simply convert all the non-boolean values to boolean in the logical expression. For example:

console.log(!![].length && true); // false

console.log(!!0 && true); // false
console.log(!!NaN && true); // false

console.log(!!'' && true); // false

console.log(!!null && true); // false
console.log(!!undefined && true); // false
// ...
console.log(true && !!'foo'); // true
console.log(true && !!1); // true
console.log(true && !![1, 2, 3].length); // true
// ...

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