1

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

ducin
  • 25,621
  • 41
  • 157
  • 256
  • http://stackoverflow.com/a/7968470/594589 – dm03514 Jun 30 '13 at 23:13
  • On a slightly related note, look at `Object.create(null)` – SLaks Jun 30 '13 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`. – Paul S. Jun 30 '13 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. – SLaks Jun 30 '13 at 23:21
  • crazy as it seems, but thank you guys – ducin Jun 30 '13 at 23:37

1 Answers1

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

ndm
  • 59,784
  • 9
  • 71
  • 110
  • 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? – ducin Jul 02 '13 at 22:13
  • 1
    Right, it's not an [object](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6), it's a [primitive value](http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.2) of the type [`Null`](http://www.ecma-international.org/ecma-262/5.1/#sec-8.2), and in a perfect world `typeof null` would return `null`. – ndm Jul 03 '13 at 09:15