ducin
ducin

Reputation: 26437

javascript null value - is it an object

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

Upvotes: 2

Views: 71

Answers (1)

ndm
ndm

Reputation: 60463

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

Upvotes: 2

Related Questions