The logical AND &&
operator actually returns the first falsy value or the last operand if no falsy value exists. For example:
console.log(false && true); // false console.log(1 && null && 'never reaches here'); // null console.log(true && 1); // 1 console.log(1 && 'will return this'); // 'will return this' console.log([].length && true); // 0 // ...
This can lead to unexpected results in places where you might actually be interested in using the result of the logical AND expression as a boolean. In such cases (where you want to always return a boolean value), you can simply convert the result of the expression to boolean using the double NOT operator or Boolean wrapper, for example, like so:
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 // ...
If, in case, you only wish to return boolean for individual values, then you can simply, only convert those specific values to boolean. For example:
console.log(1 && !![].length); // false console.log(1 && !!0); // false console.log(1 && !!NaN); // false console.log(1 && !!''); // false console.log(1 && !!null); // false console.log(1 && !!undefined); // false // ...
console.log(true && !!'foo'); // true console.log(true && !!1); // true console.log(true && !![1, 2, 3].length); // true // ...
This post was published (and was last revised ) 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.