If null
is a primitive, why does typeof(null)
return "object"
?
Because the spec says so.
11.4.3 The typeof
Operator
The production UnaryExpression : typeof
UnaryExpression is evaluated as follows:
- Let val be the result of evaluating UnaryExpression.
- If Type(val) is Reference, then
a. If IsUnresolvableReference(val) is true, return "
undefined
". b. Let val be GetValue(val). - Return a String determined by Type(val) according to Table 20.
From the MDN page about the behaviour of the typeof
operator:
// This stands since the beginning of JavaScript typeof null === 'object';In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0.
null
was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the "object"typeof
return value. (reference)A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in
typeof null === 'null'
.
This page has a nice description of the history here surrounding why typeof(null)
gives "object":
JS Data Types - Null
Here is the relevant portion (although I would suggest you read the whole post):
Why does typeof null
return "object"
?
// What's happening here?
>typeof null === "object"; // true
The answer might disappoint some, but the truth is simply because the table above says to do so.
The reasoning behind this is that null
, in contrast with undefined
, was (and still is) often used where objects appear. In other words, null
is often used to signify an empty reference to an object. When Brendan Eich created JavaScript, he followed the same paradigm, and it made sense (arguably) to return "object"
. In fact, the ECMAScript specification defines null
as the primitive value that represents the intentional absence of any object value (ECMA-262, 11.4.11).
To draw a parallel here, consider typeof(NaN) === "number"
. So why does JavaScript give "number" as the type of NaN
(not a number)? It is because NaN
is used where numbers appear, it is a value that represents the intentional absence of a number value. Similar reasoning applies to null
, the only difference being that null
is implemented as a primitive and NaN
is actually implemented as a Number
object (so NaN.foo = 42
would actually work).