Inspecting a value's type
A variable may hold different kinds of values and code needs a quick type-name check.
JS Puzzles · Const
typeof null returns "object", even though null is a separate JavaScript type and is not an object. This historical behavior is retained for compatibility.
null is a standalone value representing nothing, emptiness, or an unknown value. Although it has its own type, typeof null produces the string "object" because of a historical language error preserved for compatibility, so strict equality is required for an exact null check.
typeof x| Name | Type | Description |
|---|---|---|
x | any JavaScript expression | The value or expression whose type name should be returned. |
A string containing the operand's type name; for null, the result is "object".
const value = null;
console.log(typeof value); // "object"
console.log(value === null); // trueUse strict equality to test for null; typeof alone reports the misleading string "object".
A variable may hold different kinds of values and code needs a quick type-name check.
A program must distinguish an absent value from an actual object.
An explanation or debugging output needs to demonstrate JavaScript's historical typeof behavior.
typeof null returns the string "object". This is a historical typeof error that JavaScript keeps for compatibility, even though null has a separate type.
Follow-up: How should null be detected? Use strict equality: value === null.
null is a special standalone value representing nothing, emptiness, or an unknown value. It is not a reference to a nonexistent object or a null pointer.
Follow-up: What does typeof report for null? It reports "object" because of the longstanding language error.
The normal form is typeof x, and typeof(x) is also valid because the parentheses are optional. The result is a string naming the operand's type.
Follow-up: What special result must be remembered? typeof null is "object", despite null not being an object.
typeofnullundefinedobject