2

I'm analysing javascript datatypes and I found something extremely strange:

> typeof null
"object"
> null instanceof Object
false

Currently I've got no idea how could I explain that. I thought that everything that has typeof === "object" will have Object.prototype in its prototype chain. If null is not an object, then why does typeof return that?

PS somebody already wrote me welcome to the wacky world of javascript ;)

5
  • stackoverflow.com/a/7968470/594589 Commented Jun 30, 2013 at 23:13
  • On a slightly related note, look at Object.create(null) Commented Jun 30, 2013 at 23:15
  • @SLaks that is slightly different, though, because you're saying "the new Object's prototype shouldn't be anything" and Object.create(null).__proto__ actually gets set to null. Commented Jun 30, 2013 at 23:20
  • @PaulS.: Yes; that's why I said "slightly related". In particular, not everything that has typeof === "object" will have Object.prototype in its prototype chain. Commented Jun 30, 2013 at 23:21
  • crazy as it seems, but thank you guys Commented Jun 30, 2013 at 23:37

1 Answer 1

2

This has historical reasons:

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

typeof null === 'object'; // This stands since the beginning of JavaScript 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 is most platforms). Consequently, null had 0 as type tag, hence the bogus typeof return value. (reference needed)

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === 'null'.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your reply, I've already accepted it, but... still I don't know the answer. Is null an object? As far as I understood, it's not, right?
Right, it's not an object, it's a primitive value of the type Null, and in a perfect world typeof null would return null.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.