Why typeof null === 'object'?

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

    An interesting story is how it came about. 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 bits: the value itself;
    1-3 bits: data type label;

    There were only five variations of the type label:
    000: object;
    1: integer;
    010: double;
    100: string;
    110: boolean;

    Accordingly, if the least significant bit was equal to one, then the remaining 31 bits were interpreted as integer. If 0 - then the type was 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) - pointer to NULL (machine code NULL pointer), that is, the label of the object and the link that its numerical representation is zero.

    So it turned out that typeof began to define null as an object - it checked the type label, which informed it that null was nothing more than an object.


    Also popular now: