Robert
Robert

Reputation: 10390

javascript null returns object when used with typeof operator

Why does typeof return object when used with null? From my understanding this is a top level property of the global object. References to official documentation would greatly help.

Upvotes: 1

Views: 138

Answers (3)

Felix Kling
Felix Kling

Reputation: 816364

Because the specification says so:

Table 20 — typeof Operator Results

 Type of val     Result
---------------------------
  Undefined    "undefined"
  Null         "object"
  Boolean      "boolean"
  Number       "number"
  String       "string"
  ...

And it is also saying:

4.3.11 null value

primitive value that represents the intentional absence of any object value

Nevertheless, null is still of data type Null and you can use null where you can use other objects (e.g. accessing a property on null throws an error instead of returning undefined (for better or worse)).

From my understanding this is a top level property of the global object.

No, null is literal, just like 5 is a number literal. undefined on the other hand is a global variable (as if it wasn't already confusing enough).

Upvotes: 2

Carlos Calla
Carlos Calla

Reputation: 6706

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

Reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59232

It is . In Javascript null is an object

Kiro Risk says

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

Upvotes: 1

Related Questions