🟨 JavaScript Q103 / 104

What is the result of typeof null?

AI-Powered Answer ✓ Answered

Understanding the `typeof` operator and its behavior with `null`.

Understanding the `typeof` Operator

The typeof operator in JavaScript is used to determine the type of a given operand. It returns a string indicating the data type of the unevaluated operand.

The Result of `typeof null`

javascript
console.log(typeof null);

When you execute typeof null in JavaScript, the returned value is "object".

Why `typeof null` is 'object'

This behavior is a well-known historical bug in JavaScript, dating back to its first implementation. In JavaScript, internal values are represented by a type tag and a value. For objects, the type tag is 0. Null was represented as the NULL pointer (0x00), and it also had 0 as its type tag. Consequently, typeof incorrectly identified null as an object.

Despite being a bug, fixing it would break a lot of existing web code, so it remains a feature of the language. It's important to remember this specific behavior when working with typeof and checking for null values, often requiring an explicit === null check.