Q13 of 40 · JavaScript

What values can `typeof` return, and what are its known quirks?

JavaScriptJuniorjavascripttypeoftype-checkingnullfundamentals

Short answer

Short answer: `typeof` returns one of: 'undefined', 'boolean', 'number', 'bigint', 'string', 'symbol', 'function', or 'object'. Notable quirks: `typeof null === 'object'` (a historical bug) and checking an undeclared variable returns 'undefined' instead of throwing.

Detail

typeof is a unary operator that returns a lowercase string describing the type of its operand. It is safe to use on undeclared variables, which makes it useful for feature detection in environments where a global might or might not exist.

The null quirk: typeof null === 'object' is a long-standing JavaScript bug from version 1. The null value is represented by a null pointer (all zeros), which the type-tag check misidentified as an object. It cannot be fixed without breaking the web.

Functions: typeof returns 'function' for callable objects, even though functions are technically objects. Convenient for function-presence guards.

Arrays: typeof [] returns 'object'. To detect arrays use Array.isArray(value).

Better type checks: For most runtime type checks, prefer instanceof, Array.isArray(), or TypeScript types rather than chaining typeof conditions.

In testing: typeof is used in custom matchers and type-guard helpers to safely check response field types before asserting on their values.

// EXAMPLE

typeof 42           // "number"
typeof "hello"      // "string"
typeof true         // "boolean"
typeof undefined    // "undefined"
typeof Symbol()     // "symbol"
typeof 42n          // "bigint"
typeof function(){} // "function"
typeof {}           // "object"
typeof []           // "object"  ← arrays are objects
typeof null         // "object"  ← historical bug!

// Safe undeclared variable check (no ReferenceError)
if (typeof window !== "undefined") { /* browser */ }

// Proper checks for special cases
Array.isArray([]);            // true — not typeof
value === null;               // true — explicit null check

// WHAT INTERVIEWERS LOOK FOR

The complete list of return values, the null quirk with an explanation, and knowing `typeof []` is 'object'. Bonus: recommending Array.isArray over typeof for arrays.

// COMMON PITFALL

Relying on typeof to distinguish null from other objects — you must add an explicit `=== null` check in combination with `typeof x === 'object'`.