JavaScript ยท Chapter 37 of 55

JavaScript typeof Operator

The `typeof` operator returns a string describing the type of a value, such as 'string', 'number', 'boolean', 'object', 'function', or 'undefined'.

It's frequently used to check argument types, guard against errors, or debug unexpected values, despite a few well-known quirks.

Common results

`typeof 'x'` is 'string', `typeof 42` is 'number', `typeof true` is 'boolean', `typeof undefined` is 'undefined', and `typeof function(){}` is 'function'.

Quirks

`typeof null` returns 'object' (a long-standing bug kept for compatibility), and `typeof NaN` returns 'number' since NaN is technically a numeric type.

Example 1 (javascript)
console.log(typeof "hi");
console.log(typeof function() {});
console.log(typeof null);
Output
string
function
object

Functions report as 'function', while null oddly reports as 'object'.

Example 2 (javascript)
let x;
console.log(typeof x);
Output
undefined

An unassigned variable has the value and type undefined.

Key points

  • typeof returns a string naming a value's type.
  • typeof null is 'object' โ€” a historical quirk.
  • typeof of a function is 'function', not 'object'.
  • typeof is useful for basic runtime type checks.
๐Ÿ’ก Note: For arrays, use Array.isArray() rather than typeof since arrays also report as 'object'.

๐Ÿ“ Quick Quiz

1. What does `typeof function(){}` return?

2. What does `typeof null` return?

3. What is the type of an unassigned variable?