Null and undefined in javascript-Collection of common programming errors

undefined is a variable on the global object which is window in browser environments. Its initial value is the primitive undefined.

Being a property on the global object, historically you could have changed its value as,

window.undefined = "42"; // or just undefined = "42"

The meaning of life is now clearly defined. But since EcmaScript-5 is out, this has been disallowed, and even though it is still a property of the global object, it has been made non-writable now.

The primitives null and undefined are not the same thing if no tampering has occurred.

Null is a data type that has the sole value null. Undefined is another data type whose sole value is the primitive undefined. You can verify whether they represent the same object or not easily.

null === undefined // false

However,

null == undefined // true

is true, because they are both casted to the boolean value false before a comparison is made. The rules for converting both these values to boolean are clearly defined in section 9.2 of the spec.

9.2 ToBoolean

Argument Type | Result
-------------------------------------------------------------------------
Undefined     | false
Null          | false
Boolean       | The result equals the input argument (no conversion).
Number        | ..
String        | ..
Object        | ..

Originally posted 2013-11-09 20:19:20.