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
  • "bigint" for bigint.
  • "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.

// test type of primitives

console.assert(typeof undefined === "undefined");

console.assert(typeof "abc" === "string");

console.assert(typeof true === "boolean");
console.assert(typeof false === "boolean");

console.assert(typeof 3 === "number");
console.assert(typeof NaN === "number");
console.assert(typeof Infinity === "number");

console.assert(typeof 3n === "bigint");
// type of user-defined objects

console.assert(typeof {} === "object");
console.assert(typeof [3, 4] === "object");
console.assert(typeof /x/ === "object");
console.assert(typeof new Map() === "object");
console.assert(typeof (new Date()) === "object");

console.assert(typeof (function () {}) === "function");
console.assert(typeof ((x) => x) === "function");
console.assert(typeof class MyClass {} === "function");
// type of standard objects.
// not a complete list

console.assert(typeof Object === "function");
console.assert(typeof Array === "function");
console.assert(typeof Map === "function");

console.assert(typeof Object.prototype === "object");
console.assert(typeof Array.prototype === "object");
console.assert(typeof Map.prototype === "object");

console.assert(typeof JSON === "object");
console.assert(typeof Math === "object");

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.