javascript

Why does null==undefined but null!=false and undefined!=false


Null and undefined are each coerced to false in the operation null==undefined. So why aren't they also coerced to false in the operations null==false or undefined==false?

let undefinedEqualsFalse = undefined == false;
let nullEqualsFalse = null == false;
let nullEqualsUndefined = null == undefined;

console.log('undefinedEqualsFalse', undefinedEqualsFalse);
console.log('nullEqualsFalse', nullEqualsFalse);
console.log('nullEqualsUndefined', nullEqualsUndefined);

output:

undefinedEqualsFalse false
nullEqualsFalse false
nullEqualsUndefined true


Solution

  • The == operator follows specific type coercion rules. null and undefined are equal to each other by special definition in JavaScript, but they don't equal false because comparison with booleans involves converting the boolean to a number first (false becomes 0), and neither null nor undefined equal 0.