The typeof operator returns one of eight strings: "string", "number", "bigint", "boolean", "undefined", "symbol", "function" or "object". It never throws on an undeclared variable, and it reports "object" for null, arrays and most other objects, which is why it is not enough to tell them apart.
Hosts can add their own results for unusual objects, but in modern browsers and Node.js the eight strings above are all you need to know.
| Operand | typeof result |
|---|---|
"text" | "string" |
42, 3.14, NaN, Infinity | "number" |
42n | "bigint" |
true, false | "boolean" |
undefined | "undefined" |
Symbol("id") | "symbol" |
function () {}, class A {} | "function" |
{}, [], null, new Date(), /re/ | "object" |
The result is always a lowercase string, so compare it with === against a string literal. Misspelling the string, as in typeof x === "strnig", silently evaluates to false; linters and TypeScript flag this.
This is a bug from the first version of JavaScript that cannot be fixed without breaking existing code. null is a primitive, so test for it directly.
typeof [] returns "object". Use Array.isArray() instead.
A class declaration is syntax over a constructor function, so typeof reports "function". Functions are callable objects, and typeof singles them out.
typeof NaN is "number". Check for it with Number.isNaN(value).
Reading an undeclared identifier throws a ReferenceError, but typeof does not. This makes it useful for feature detection.
There is one exception. A variable declared with let, const or class is in the temporal dead zone before its declaration runs, and typeof on it throws a ReferenceError.
Because typeof is coarse for objects, combine it with other checks.
Use instanceof for class instances, Array.isArray() for arrays, Number.isFinite() for real numbers, and Object.prototype.toString.call() when you need the internal class tag. In TypeScript, typeof also works as a type guard that narrows a union type.
"undefined", "boolean", "number", "bigint", "string", "symbol", "function" and "object".
Use Array.isArray(value). typeof returns "object" for arrays.
No. It is an operator, not a function, so typeof x and typeof(x) are equivalent. The parentheses only group the operand.
typeof x === "undefined" is safe for undeclared names. For properties, use "key" in obj or optional chaining such as obj?.key.
typeof returns one of eight lowercase strings. It is reliable for primitives and functions, but it reports "object" for null, arrays and most built-in objects, so pair it with === null, Array.isArray() and instanceof. Remember that it is safe on undeclared variables, except for those in the temporal dead zone.