Back to basics: null vs. undefined
null and undefined are two special values in Javascript used to represent non-values. There are two of such non-values because
- JavaScript was designed with Java's type system in mind and borrowed
nullto represent not an object. - Early JavaScript handles error silently, leading to unexpected bugs.
undefinedwas added to indicate no such value. This is used when a property/value is expected to happen but didn't show up.
So, with these in mind, let's take a look at where we can find these values.
Values and operators
Since undefined is used to indicate missing property and value, all non-existing variables/properties and uninitialised variables/properties would have a value of undefined. A deleted element also has a value of undefined as a placeholder for the element. (Please note that delete array[index] does not remove the element, merely setting it to undefined)
undefined is also a property on the global object (global in Node environment and window in browser environment).
void operator is used to return undefined for any value provided as the operand. There are a couple of reasons why you would want to use void instead of undefined
-
undefinedvalue could be overshadowed by other values. - Before ES5, there was no read-only property, so value of
undefinedcan be overridden.
null, on the other hand, is used where no object is expected. You can find null as the result of Object.getPrototypeOf(Object.prototype)
Types and value
Both undefined and null are primitive values. undefined is a type of itself, while null indicates emptiness
Coercion
undefined represents values that are missing, so when coerced, or converted to numeric type, it will become NaN, whereas null represents no value and when coerced, it will become 0.