JS: “typeof” Operator

By Xah Lee. Date: . Last updated: .

typeof value → return a string that represents the type of value.

Return one of:

[see JS: Value Types]

console.log ( typeof undefined === "undefined" ); // true
console.log ( typeof "abc" === "string" ); // true
console.log ( typeof true === "boolean" ); // true
console.log ( typeof false === "boolean" ); // true
console.log ( typeof 3 === "number" ); // true
console.log ( typeof NaN === "number" ); // true
console.log ( typeof Infinity === "number" ); // true
// type of some standard objects
// following are all true

console.log( typeof {} === "object" );

console.log( typeof [3,4] === "object" );

console.log( typeof (new Date()) === "object" );

console.log( typeof /x/ === "object" ); // this is regex object

console.log( typeof JSON === "object" );

console.log( typeof Math === "object" );

[see JavaScript Object Reference]

Type of null

typeof null return "object". This is historical bug and we are stuck with it. (it should return "null")

[see JS: null]

Type of function

typeof function return "function". This is really useful, but is a JavaScript quirk, because, by spec, “function” is not one of defined type of values.

[see JS: Value Types]

console.log(
    typeof (function () {}) === "function"
); // true

The data type of JavaScript function actually is object, by spec.

ECMAScript® 2016 Language Specification#sec-terms-and-definitions-function

[see JS: Object Type]

Determine Subtype of Object

[see JS: Determine Type of Object]

“typeof” is a Operator

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.

ECMAScript 2015 §ECMAScript Language: Expressions#sec-typeof-operator

JS Types Topic

  1. JS: Value Types
  2. JS: Primitive Value
  3. JS: Object Type
  4. JS: “typeof” Operator
  5. JS: Determine Type of Object
  6. JS: Object.prototype.isPrototypeOf
  7. JS: Property Key “constructor”
  8. JS: “instanceof” Operator
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.