JavaScript Reference ยท Operators
The typeof operator
Reference for the JavaScript typeof operator: every possible result, the null and function quirks, checking undeclared variables and better type checks.
The typeof operator returns a string that names the type of its operand. It is the quickest way to tell primitives apart ("string", "number", "boolean", ...) and to check whether a value is a function.
It has two famous quirks: typeof null is "object" (a historical mistake that can't be fixed), and every non-function object, including arrays, gives "object".
typeof value typeof(value)
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
typeof operand
| Value | Result |
|---|---|
undefined |
"undefined" |
null |
"object" |
true or false |
"boolean" |
any number, including NaN and Infinity |
"number" |
| a BigInt | "bigint" |
| a string | "string" |
| a Symbol | "symbol" |
| a function or class | "function" |
| any other object (arrays, dates, maps, ...) | "object" |
Return value: one of the strings above.
Exceptions: typeof of an undeclared identifier does not throw, but typeof of a let, const or class binding still in its temporal dead zone throws a ReferenceError.
Usage notes
- Check for null separately:
typeof x === "object" && x !== nullis the usual test for "a real object". - Arrays: use
Array.isArray(). UseinstanceoforObject.prototype.toString.call()for other built-in classes. NaNis a number. UseNumber.isNaN()to detect it.- Functions:
typeof f === "function"works for normal functions, arrow functions, async functions and classes (calling a class withoutnewstill throws). - Safe feature checks:
typeof window !== "undefined"tells you whether code runs in a browser, without aReferenceErroron the server. - Parentheses are optional:
typeof (x)is the same astypeof x.typeof x + 1is"number1", becausetypeofbinds tighter than+. - Wrapper objects:
typeof new String("a")is"object", whiletypeof String("a")is"string". - Strings only: the result is always one of a fixed set of strings, so compare with
===and watch spelling ("undefined", not"undefine").
Browser support
Supported in every browser and runtime. The "bigint" and "symbol" results exist wherever those types do (all current browsers).