why null==undefined is true in javascript

Using the double-equal operator forces Javascript to do type coercion.

In other words, when you do x == y, if x and y are not of the same type, JavaScript will cast one value to another before comparing, like if string and number are compared, the string is always cast into a number and then compared

For this reason, many comparisons of mixed types in JavaScript can result in results that may be unexpected or counter-intuitive.

If you want to do comparisons in JavaScript, it is usually a better idea to use the triple-equal operator === rather than double-equal. This does not do a type coercion; instead if the types are different, it returns false. This is more usually what you need.

You should only use double-equal if you are absolutely certain that you need it.


The language specification explicitly says:

If x is null and y is undefined, return true

I'm not aware of any records of the language design process that explain the reasoning for that decision, but == has rules for handling different types, and "null" and "undefined" are both things that mean "nothing", so having them be equal makes intuitive sense.

(If you don't want type fiddling, use === instead).

Tags:

Javascript