Bucket
Bucket

Reputation: 7521

Why does typeof(null) return "object", but you can't assign properties to it?

Bear with me here, I'm going to try something stupid.

When I evaluate typeof(null) in the console, I get "object", so logically, I should be able to assign properties to it, but null.foo = 42 gives TypeError: Cannot set property 'foo' of null.

Is Javascript just picky when it comes to which global objects are mutable?

Upvotes: 4

Views: 3985

Answers (3)

Andrew Clark
Andrew Clark

Reputation: 208455

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

Upvotes: 11

Landon Sanders
Landon Sanders

Reputation: 19

null is a primitive data type. it has one value: null. it does not have a constructor. it is an object that is build in to the language. you can't create an object of the type null, in other words.

Upvotes: -1

bfavaretto
bfavaretto

Reputation: 71908

The specification determines that typeof should return "object" for the null value, and at the same time defines null as a primitive:

A primitive value is a member of one of the following built-in types: Undefined, Null, Boolean, Number, and String; an object is a member of the remaining built-in type Object; and a function is a callable object.

So, null is not an object. That's why you can't assign properties to it. The value returned by typeof is artificial.

Upvotes: 4

Related Questions