Why does JavaScript even have null?
JavaScript has its quirks and difficulties. One of them is null & undefined. If there’s undefined, why does JavaScript even have null?
Equality
Let’s start exploring null and undefined by having a look at the following comparisons:
How can null be bigger or equal to zero, less or equal to zero, but not be equal to zero?!
To understand this we have to know how JavaScript handles these comparisons. There are two different kinds of operators used in the example above: Equality Operators (==, ===, != and !===) and Relational Operators (>, <, >= and <=). And both work differently.
Equality operators compare at an object level. If both _operands, _the things left and right of the operator, are of different types a strict comparison (=== or !==) is used. Because null is an object and 0 is a number they are not equal.
In the case of Relational Operators, both operands are converted to the same type. In the example to a number. Under the hood, JavaScript is doing the following:
Which makes much more sense. Number(null) return the value 0 and 0 is equal to 0.
Let’s try the same examples with undefined:
First thought would be that this should result in the same outcome. Although JavaScript is doing the same, the result is different. Again, JavaScript is converting undefined to a number, but Number_(undefined)_ is not 0 but NaN. The JavaScript spec says that every comparison with NaN results in false, even a comparison with NaN.
There’s even a little bit more to the _ comparison algorithm _than this, but this explains the idea.
Why null?
Does JavaScript need a null value? Though it would be possible to write an entire application without using null, and often it does, there is a place for null. The difference in usage is intention. A null value is intenionally abcent, where an undefined value is often unintentional and just the default value.
For example in a function retrieving a piece of data. When that data isn’t there, this function returns null. Otherwise, it returns the data. This way one can tell if the value is returned by the function and is set to null or if the variable that should contain the result isn’t set at all.
In other words: null !== undefined