JS: null
What is null
null
is a literal expression, e.g. you can writelet x = null;
null
is one of the type of JavaScript values, and it is the only value of that type. 〔see Value Types〕
typeof null
typeof null
return "object"
.
(this is a historical bug.
typeof null
should return "null"
)
typeof null === "object"
Why “typeof null” return "object"
typeof null
return "object"
is a historical implementation bug. Now we are stuck with it.
null
is not a object, because It doesn't have the defining quality of JavaScript objects, namely, it's not a collection of (key and value) pairs; you cannot add properties to null
.
// null.p = 4; // TypeError: Cannot set property 'p' of null
The history of “typeof null” By Dr Axel Rauschmayer. At https://2ality.com/2013/10/typeof-null.html
What is the Use of null
There are 2 major uses of null
.
- you can set a object's prototype (parent) to
null
, to make it having no prototype. 〔see Get Set Prototype〕 Or, use Object.create withnull
to create a object with no parent. - You can set a variable to
null
as default initial value. (unassigned variable has default value ofundefined
. 〔see undefined〕).