In JavaScript:
console.log(typeof null); // "object"
So, null appears as an object, even though it is not really an object.
Why typeof null is "object"
- This is a historical bug in JavaScript.
- In the early implementation, values were stored in a type tag system, where objects had a type tag of
0. nullwas represented as a null pointer (0), sotypeof nullreturned"object".- It has been kept for backward compatibility.
Important Points
nullrepresents intentional absence of any object value.- It is different from
undefined, which means a variable has been declared but not assigned a value.
let a;
console.log(a); // undefined
console.log(typeof a); // "undefined"
let b = null;
console.log(b); // null
console.log(typeof b); // "object"
- Use
===for checks to avoid type coercion:
console.log(b === null); // true
console.log(b == null); // true (also matches undefined)
⚡ In short:
nullis a primitive that represents no value, buttypeof nullreturns"object"due to a historical JavaScript bug. Always use strict checks (=== null) to identify it.