Hiprup

What is the typeof operator and its quirks?

typeof returns a string naming a value's type, but it has well-known quirks.

  • Reliable — "string", "number", "boolean", "undefined", "function", "symbol", "bigint".

  • typeof null — "object" (a bug); check with === null.

  • typeof [] — "object"; use Array.isArray.

Bottom line: great for primitives and functions; for arrays and null, use dedicated checks.

console.log(typeof 42);            // 'number'
console.log(typeof 'hello');       // 'string'
console.log(typeof true);          // 'boolean'
console.log(typeof undefined);     // 'undefined'
console.log(typeof Symbol());      // 'symbol'
console.log(typeof 42n);           // 'bigint'
console.log(typeof function(){});  // 'function'
console.log(typeof {});            // 'object'

// Quirks
console.log(typeof null);          // 'object' (BUG!)
console.log(typeof []);            // 'object' (use Array.isArray)
console.log(typeof NaN);           // 'number' (NaN is numeric)

// Safe checks
console.log(Array.isArray([]));          // true
console.log(value === null);              // true for null
console.log(Number.isNaN(NaN));           // true for NaN

typeof correctly identifies 7 types. Three quirks: null='object' (bug), []='object' (arrays are objects), NaN='number' (NaN is numeric type).

Use Array.isArray for arrays, === null for null, Number.isNaN for NaN.

Know the three quirks: typeof null='object', typeof []='object', typeof NaN='number'. Show the correct alternatives: Array.isArray, === null, Number.isNaN. typeof is safe on undeclared variables (returns 'undefined' without throwing).

What is the typeof operator and its quirks? | Hiprup