JS: 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.

πŸ’‘ TIP: typeof is a operator, not a function. This means, you do not need parenthesis for the argument. e.g. typeof 3 is valid. Use parenthesis typeof(expr) only when expr is complicated.

console.log(
  typeof undefined === "undefined",
  typeof "abc" === "string",
  typeof true === "boolean",
  typeof false === "boolean",
  typeof 3 === "number",
  typeof NaN === "number",
  typeof Infinity === "number",
);

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

Null is Not an Object

πŸ›‘ WARNING: typeof null return "object" is a bug and we are stuck with it. (it should return "null") [see null]

Function is Also Object

πŸ›‘ WARNING: 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