undefined
and null
are two very special values in JavaScript. They are both of its own data type, and they both indicate the lack of something meaningful. In most cases, you can treat them as the same thing.
When you apply the typeof
operator on undefined
, it returns undefined
.
1typeof undefined;
This proves that undefined
is of its own data type. When a variable is initialized without a value, it will be assigned undefined
automatically. It represents the absence of a meaningful value.
null
is very similar. It defines an empty value. A value exists, but it is empty.
The fact that there are two values defining the same thing is just a mistake in JavaScript's design. In most cases, you can see them as interchangeable.
In fact, when you compare them, JavaScript will tell you they are the same.
1undefined == null;
But when you use ===
(equal value and equal type), JavaScript will return false
.
1undefined === null;
That's because they are both unique and of different data types.
However, when you apply the same typeof
operator on null
. JavaScript will tell you it is an object.
1typeof null; // -> object
This is actually another mistake in JavaScript. null
is of type null
, not an object. The only reason that JavaScript hasn't fixed these mistakes is that it might break some older software.