I am reading 'Professional Javascript for Web Developers' Chapter 4 and it tells me that the five types of primitives are: undefined, null, boolean, number and string.
If null
is a primitive, why does typeof(null)
return "object"
?
Wouldn't that mean that null
is passed by reference (I'm assuming here all objects are passed by reference), hence making it NOT a primitive?
In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value, with the type tag for objects being
0
, andnull
was represented as theNULL
pointer (0x00
on most platforms). As a result, null had0
as a type tag, hence the bogustypeof
return value (reference).A "fix" was proposed for ECMAScript (via an opt-in). It would have resulted in:
... but this change was rejected, due to issues with code using this specific "quirk" to test for
null
.Because the spec says so.
in short: it is bug in ECMAScript, and the type should be
null
reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
From the book YDKJS
As has been pointed out, the spec says so. But since the implementation of JavaScript predates the writing of the ECMAScript spec, and the specification was careful not to correct foibles of the initial implementation, there's still a legitimate question about why it was done this way in the first place. Douglas Crockford calls it a mistake. Kiro Risk thinks it kinda sorta makes sense: