typeof

Returns a string with the name of a value’s type, e.g. "number", "string", or "object".

Returns
A string with the type name: "undefined", "boolean", "number", "bigint", "string", "symbol", "function", or "object".
On this page

Example

#
JavaScript
console.log(typeof 42)
console.log(typeof 'Emma')
console.log(typeof true)
console.log(typeof undefined)
console.log(typeof { level: 1 })
console.log(typeof (() => {}))
Console
number
string
boolean
undefined
object
function

Definition and usage

#

The typeof operator checks what type a value is and returns the answer as a string. The possible results are: "undefined", "boolean", "number", "bigint", "string", "symbol", "function", and "object".

It’s useful for checking function arguments and data from the outside, like whether a user actually provided a number. You can even use it on an undeclared variable: it then returns "undefined" instead of an error, which is why it’s used to check whether some API exists in the environment.

It has two well-known pitfalls. typeof null returns "object", which is a historical bug in the language. Arrays are also "object", so Array.isArray() is what you use to recognize them. It’s also worth remembering that NaN has the type "number".

Syntax

#
Syntax
typeof operand
typeof (expression)

More examples

#
Pitfalls: null, arrays, and NaN
JavaScript
console.log(typeof null)
console.log(typeof [1, 2, 3])
console.log(Array.isArray([1, 2, 3]))
console.log(typeof NaN)
Console
object
object
true
number
Checking an argument
JavaScript
function addPoints(current, amount) {
  if (typeof amount !== 'number' || Number.isNaN(amount)) {
    return current
  }
  return current + amount
}

console.log(addPoints(100, 20))
console.log(addPoints(100, '20'))
Console
120
100
An undeclared variable and feature detection
JavaScript
console.log(typeof notDeclared)

if (typeof structuredClone === 'function') {
  console.log('structuredClone() is available')
}
Console
undefined
structuredClone() is available

A plain read of an undeclared variable throws a ReferenceError, while typeof returns "undefined" instead. The exception is let and const variables used before their declaration: there you still get an error.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • To check for null, use value === null, and for arrays, Array.isArray(value). typeof returns "object" for both.
  • You recognize class instances, like Date or your own, with the instanceof operator. typeof simply returns "object" for them.
  • Mind the precedence: typeof a + b is (typeof a) + b. To check the type of an expression’s result, add parentheses: typeof (a + b).

Related entries

#

Spotted a mistake or missing an example? Write to us.