JavaScript: typeof Operator

By Xah Lee. Date: . Last updated: .
typeof value
Return a string that represents the Type of value.

Return one of:

  • "object" for Object or null.
  • "function" for function.
  • "string" for string.
  • "number" for number, including NaN and Infinity
  • "undefined" for undefined.
  • "boolean" for true or false.
console.log(typeof undefined === "undefined");
console.log(typeof "abc" === "string");
console.log(typeof true === "boolean");
console.log(typeof false === "boolean");
console.log(typeof 3 === "number");
console.log(typeof NaN === "number");
console.log(typeof Infinity === "number");

// type of some standard objects
console.log(typeof {} === "object");
console.log(typeof [3, 4] === "object");
console.log(typeof (new Date()) === "object");
console.log(typeof /x/ === "object");
console.log(typeof JSON === "object");
console.log(typeof Math === "object");
console.log(typeof (function () {}) === "function");
console.log(typeof ((x) => x) === "function");

// all true

Note: typeof is a operator, not a function. This means, you can write typeof 3, no need parenthesis. Use parenthesis typeof(expr) only when expr is complicated.

Warning: Null is Not an Object

typeof on null is historical bug and we are stuck with it. (it should return "null") [see null]

Warning: Function is Also Object

by JavaScript spec, there is no value type named β€œfunction”. typeof return "function" is a programing convenience.

JavaScript Value Types

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc