I want to know what the difference is between null
and undefined
in JavaScript.
The best way to understand the difference is to first clear your mind of the inner workings of JavaScript and just understand the differences in meaning between:
let supervisor = "None"
// I have a supervisor named "None"
let supervisor = null
// I do NOT have a supervisor. It is a FACT that I do not.
let supervisor = undefined
// I may or may not have a supervisor. I either don't know
// if I do or not, or I am choosing not to tell you. It is
// irrelevant or none of your business.
There is a difference in meaning between these three cases, and JavaScript distinguishes the latter two cases with two different values, null
and undefined
. You are free to use those values explicitly to convey those meanings.
So what are some of the JavaScript-specific issues that arise due to this philosophical basis?
A declared variable without an initializer gets the value undefined
because you never said anything about the what the intended value was.
let supervisor;
assert(supervisor === undefined);
A property of an object that has never been set evaluates to undefined
because no one ever said anything about that property.
const dog = { name: 'Sparky', age: 2 };
assert(dog.breed === undefined);
null
and undefined
are "similar" to each other because Brendan Eich said so. But they are emphatically not equal to each other.
assert(null == undefined);
assert(null !== undefined);
null
and undefined
thankfully have different types. null
belongs to the type Null
and undefined
to the type Undefined
. This is in the spec, but you would never know this because of the typeof
weirdness which I will not repeat here.
A function reaching the end of its body without an explicit return statement returns undefined
since you don't know anything about what it returned.
By the way, there are other forms of "nothingness" in JavaScript (it's good to have studied Philosophy....)
NaN
ReferenceError
let
or const
defined local variable in its temporal dead zone and receiving a ReferenceError
Empty cells in sparse arrays. Yes these are not even undefined
although they compare ===
to undefined.
$ node
> const a = [1, undefined, 2]
> const b = [1, , 2]
> a
[ 1, undefined, 2 ]
> b
[ 1, <1 empty item>, 2 ]