null
// This stands since the beginning of JavaScript
typeof null === 'object';
Short Answer:
This is a bug since the first release of ECMAScript which
unfortunately can’t be fixed because it would break the existing code.
Explanation:
However, there is actually one logical explanation behind why null is an object in javascript.
In the initial version of JavaScript, values were stored in 32 bit units which consisted of a small type tag (1–3 bits) and the actual data of the value. The type tags were stored in the lower bits of the units.
There were five of them:
000: object. The data is a reference to an object.
1: int. The data is a 31 bit signed integer.
010: double. The data is a reference to a double floating point number.
100: string. The data is a reference to a string.
110: boolean. The data is a boolean.
For all objects it was 000 as the type tag bits. null was considered to be a special value in JavaScript from its very first version. null was a representation of the null pointer. However, there were no pointers in JavaScript like C. So null simply meant nothing or void and was represented by all 0’s. Hence all its 32 bits were 0’s. So whenever the JavaScrit interpreter reads null, it considers the first 3 bits as type “object”. That is why typeof null returns “object”.
Resource:
https://2ality.com/2013/10/typeof-null.html#:~:text=In%20JavaScript%2C%20typeof%20null%20is,it%20would%20break%20existing%20code.
Note:
A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in
typeof null === 'null'.
$.type(null)
would return"null"
, for some reason .... – Insulatortypeof
is an operator and not a function, so the parentheses in your code are not necessary - you could simply use the syntaxtypeof null
. – Footloose(typeof +(\w+) +={2,3} +"object")
to ->($2 && $1)
in order to fix this issue anywhere it may exist. This will turntypeof arg === "object"
into(arg && typeof arg === "object")
– Hypogeousif (typeof x !== 'object' || x === null)
and moved on... – Spittoon