Skip to content

Latest commit

 

History

History
66 lines (42 loc) · 3.56 KB

typeof-null-why-its-object.md

File metadata and controls

66 lines (42 loc) · 3.56 KB

If null is a primitive, why does typeof(null) return "object"?

Explanation-1

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:

  1. Let val be the result of evaluating UnaryExpression.
  2. If Type(val) is Reference, then    a. If IsUnresolvableReference(val) is true, return "undefined".    b. Let val be GetValue(val).
  3. Return a String determined by Type(val) according to Table 20.

enter image description here


Explanation-2

From the MDN page about the behaviour of the typeof operator:

null

// 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'.


Explanation-3

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).