Home > Web Front-end > JS Tutorial > Why Does `typeof null` Return 'object' in JavaScript?

Why Does `typeof null` Return 'object' in JavaScript?

Mary-Kate Olsen
Release: 2024-12-03 22:38:09
Original
735 people have browsed it

Why Does `typeof null` Return

Why Does typeof Null Return "Object" Despite Not Being a Primitive Type?

While reading "Professional Javascript for Web Developers," you encounter a perplexity: the chapter states that primitives include null, yet typeof(null) yields "object." As primitives are typically passed by value and objects by reference, this seemingly contradicts null's primitive nature.

Historical Root of Type Manipulation

Diving into the annals of JavaScript, we discover that this anomaly stems from the initial implementation of the language. In the infancy of JavaScript, values were characterized by a type tag and a value. Objects had a type tag of 0. Null, represented by the NULL pointer (0x00), was inadvertently assigned a type tag of 0.

Remains of the Past

This accidental association of null with the "object" type tag led to the erroneous typeof(null) result. Despite subsequent updates and advancements in the language, this behavior persisted, hampered by concerns of disrupting existing code.

Fix Proposed but Rejected

Efforts were made to rectify this issue by proposing an optional fix in ECMAScript, intending to return typeof(null) as "null." However, the proposition faced rejection. Its implementation would have introduced a significant change, potentially breaking legacy code that relied on the existing behavior.

Current Situation

Consequently, the peculiar typeof(null) behavior remains embedded within the fabric of JavaScript. Type manipulation in JavaScript continues to be a nuanced and historically influenced aspect of the language, exemplified by this enduring quirk.

The above is the detailed content of Why Does `typeof null` Return 'object' in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template