Problem Statement
What does typeof null return in JavaScript?
Explanation
Typeof null returns object, but this is actually a bug in JavaScript.
Null is a primitive type, not an object. This bug has existed since JavaScript was created in 1995.
Why was it not fixed:
If JavaScript fixed this bug now, millions of websites would break. Many websites check if something is an object using typeof. Changing it would cause chaos.
How to correctly check for null:
Never use typeof to check for null. Use triple equals instead.
Write: if (value === null)
Code Solution
SolutionRead Only
// The famous typeof null bug
console.log(typeof null); // 'object' (WRONG but cannot fix)
console.log(typeof undefined); // 'undefined' (correct)
// Other typeof examples
console.log(typeof 42); // 'number'
console.log(typeof 'hello'); // 'string'
console.log(typeof true); // 'boolean'
console.log(typeof {}); // 'object'
console.log(typeof []); // 'object' (arrays are objects)
// WRONG way to check for null
if (typeof value === 'object') {
// This could be null OR an object OR an array!
}
// CORRECT way to check for null
if (value === null) {
console.log('Value is null');
}
// Check for null or undefined
if (value == null) {
// True for both null and undefined
}
// Detailed null check
if (value !== null && typeof value === 'object') {
console.log('It is an object, not null');
}Practice Sets
This question appears in the following practice sets:
