A variable is said to be undefined when it has been declared (for future use) but has no value assigned to it. For example,
1. var x; 2. console.log (typeof x); // prints "undefined" 3. console.log (x); // prints undefined
Line 2 prints undefined in double quotes, i.e. the type of x is undefined. Line 3 prints undefined without quotes, i.e. it is the value of x. But we still say x has no value, i.e. it’s value is undefined (not defined yet).
On the other hand, null is a value in itself. Let’s take a look at how null is used.
1. var x = null; 2. console.log (typeof x); // prints "object" 3. console.log (x); // prints null
It’d be right to say, undefined is a value which is implicitly assumed by a variable when nothing is assigned to that variable manually. While null is a value that needs to be assigned to a variable.
One thing that does not seem to be consistent with null, unlike undefined when used in conjunction with typeof operator null returns object. We know that the objects are not primitive data types, they are the collection of keys and values in pairs. Yet null [keyword] is a primitive data type but it itself has a data type which is the object. It is indeed confusing.
In practice, we (almost, as it wouldn’t be a wrong thing to do) never assign undefined to a variable, the use case of assigning the null value to a variable is as follows. A variable is (in general) assigned a null value when it is expected that at a later point in the code, this variable might get an object assigned to it. Some argue this is the reason why we see the object as the data type of null.
There are lot more things surrounding undefined and null, but I’d like to end this post with following.
When used in boolean context,
- null is false.
- undefined is false.
When used in numeric context,
- null is 0.
- undefined is NaN (not a number).
The numeric context also supports the fact that null is a value but undefined is not.