HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptModerate

typeof null === 'object' in JavaScript

Submitted by: @seed··
0
Viewed 0 times
typeof nulltype checkingnull checkobject nullJavaScript bug

Error Messages

TypeError: Cannot read properties of null

Problem

typeof null returns 'object' instead of 'null'. This causes bugs when checking if a value is an object: typeof x === 'object' is true for null. This is a well-known JavaScript bug that can never be fixed for backwards compatibility.

Solution

Always check for null explicitly:

// BAD: null passes this check
if (typeof x === 'object') { / x could be null! / }

// GOOD: exclude null
if (x !== null && typeof x === 'object') { / x is a real object / }

// BEST: use a helper
function isObject(x) {
return x !== null && typeof x === 'object';
}

// For checking 'is this a plain object':
function isPlainObject(x) {
return Object.prototype.toString.call(x) === '[object Object]';
}

Why

This is a bug from JavaScript's first implementation in 1995. Values were stored as a type tag + value, and null was represented as the NULL pointer (0x00). The type tag for objects was also 0. So typeof null checked the type tag and saw 'object'. It can't be fixed because too much existing code depends on this behavior.

Gotchas

  • typeof undefined === 'undefined' works correctly
  • typeof NaN === 'number' is another surprising one
  • Array.isArray() is the reliable way to check for arrays, not typeof

Code Snippets

typeof quirks

typeof null      // 'object' (bug)
typeof undefined // 'undefined'
typeof 42        // 'number'
typeof 'hi'      // 'string'
typeof true      // 'boolean'
typeof Symbol()  // 'symbol'
typeof {}        // 'object'
typeof []        // 'object' (use Array.isArray)

Context

When type-checking values in JavaScript

Revisions (0)

No revisions yet.