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?
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 withundefined
, 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 definesnull
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With