📜 ⬆️ ⬇️

Why typeof null === 'object'?

All JavaScript programmers have long been accustomed to the fact that typeof null === 'object'; // true typeof null === 'object'; // true , although in fact null is a primitive value. Many people know that this is a bug, and Brendan Ike personally admits this. This bug will probably never be fixed due to the need to preserve the backward compatibility of existing code with new versions of the language.

An interesting story of how it happened. It goes back to the first version of the language, namely to the fact that the values ​​of variables were stored in 32-bit cells in the following format:
29-31 bit: the value itself;
1-3 bits: data type label;

There were only five types of label types:
000: object;
1: integer;
010: double;
100: string;
110: boolean;
')
Accordingly, if the low bit was equal to one, then the remaining 31 bits were interpreted as integer. If 0, the type is determined depending on the value of the next two bits.

There were also two special reserved values:

undefined (JSVAL_VOID) - integer –2 30
null (JSVAL_NULL) is a pointer to NULL (machine code NULL pointer), that is, the label of the object and a link to the fact that its numerical representation is zero.

So it turned out that typeof began to define null as object - he checked the type label, which informed him that null is nothing but object.

via

Source: https://habr.com/ru/post/200664/


All Articles