Sub topic 3
Inspecting Types with typeof
This chapter assumes you know the seven primitive types and the object type, and that objects are shared by reference rather than copied. You should also be comfortable running snippets in a browser console or Node.js.
The typeof operator is the first tool most developers use to ask what kind of value they have. It is fast, it works on any value, and it never needs a library. It also has a few quirks, so you need an accurate picture of what it reports and where that picture stops matching the eight types.
What typeof Returns
typeof is a unary operator. You write it before an expression, and it evaluates to a string. That string is always one of exactly eight values:
| Value category | `typeof` result |
|---|---|
| undefined | `"undefined"` |
| boolean | `"boolean"` |
| number (including `NaN` and `Infinity`) | `"number"` |
| bigint | `"bigint"` |
| string | `"string"` |
| symbol | `"symbol"` |
| object that can be called (functions, classes) | `"function"` |
| null, and any other object | `"object"` |
The eight result strings do not map one to one onto the eight types. The language has a null type, but typeof never returns "null". The language has no separate function type, but typeof returns "function" anyway. Most typeof surprises come from these two mismatches.
console.log(typeof 42); // "number"
console.log(typeof NaN); // "number": NaN is a Number value
console.log(typeof 10n); // "bigint"
console.log(typeof "hi"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof null); // "object" (a long-standing quirk)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function () {}); // "function"How the Result Is Chosen
The specification defines typeof as a short decision table. Primitives are matched by their type. For objects, the only question is whether the object can be called. An object can be called when it has an internal [[Call]] method, and every function has one.
This explains several results that look odd at first:
- Classes are functions underneath, so
typeof class {}is"function". - Arrow functions, async functions, generator functions, and bound functions are all callable, so each reports
"function". - Arrays, dates, regular expressions, maps, sets, and promises cannot be called, so they all report
"object".
console.log(typeof class Point {}); // "function"
console.log(typeof (() => {})); // "function"
console.log(typeof async function () {}); // "function"
console.log(typeof Math.max.bind(null)); // "function"
console.log(typeof new Date()); // "object"
console.log(typeof /abc/); // "object"
console.log(typeof new Map()); // "object"
console.log(typeof Promise.resolve(1)); // "object"The typeof null Quirk
typeof null === "object" is a bug from the first implementation of JavaScript in 1995. Values carried a small type tag in their low bits, and the tag for objects was 0. null was represented as the null pointer, which is all zero bits, so its tag read as "object". Fixing this was proposed for ES2015 and rejected because too much existing code depended on the old result.
The practical result is that typeof x === "object" does not prove you can read properties from x:
function describe(x) {
if (typeof x === "object") {
return Object.keys(x).length; // throws when x is null
}
return 0;
}
console.log(describe({ a: 1 })); // 1
try {
describe(null);
} catch (err) {
console.log(err instanceof TypeError); // true
}Wrapper Objects Report "object"
When you call Number, String, or Boolean with new, you get a wrapper object, not a primitive. typeof reports what you actually have:
console.log(typeof 5); // "number"
console.log(typeof new Number(5)); // "object"
console.log(typeof Number("5")); // "number": no new, so a primitive
console.log(typeof new String("hi")); // "object"
console.log(typeof Object(Symbol("s"))); // "object"This is one reason to avoid new Number and its relatives. A value that prints like 5 but fails a typeof x === "number" check causes confusing bugs.
typeof and Undeclared Variables
typeof is the one place where you can name a variable that does not exist without getting an error. If an identifier cannot be resolved, typeof returns "undefined" instead of throwing a ReferenceError.
console.log(typeof someNameThatWasNeverDeclared); // "undefined"
// console.log(someNameThatWasNeverDeclared); // ReferenceError
// Common feature detection for code that runs in several environments
const inBrowser = typeof window !== "undefined";
console.log(inBrowser);This safety does not cover the temporal dead zone. The temporal dead zone is the stretch of a block before a let, const, or class declaration runs. In that stretch, the binding exists but is not initialized, and typeof throws:
try {
console.log(typeof later); // ReferenceError: cannot access before initialization
let later = 1;
} catch (err) {
console.log(err.name); // "ReferenceError"
}typeof also cannot tell a declared variable holding undefined from a name that was never declared. Both report "undefined".
Precedence Gotchas
typeof binds more tightly than binary operators, so it applies only to the operand right after it:
const n = 5;
console.log(typeof n + "px"); // "numberpx": (typeof n) + "px"
console.log(typeof (n + "px")); // "string"
console.log(typeof typeof n); // "string": typeof always returns a string
console.log(typeof n === "number"); // true: typeof runs before ===Since typeof always produces a string, comparing its result with === is always safe. No coercion is involved. A typo in the compared string fails silently, though. typeof x === "nubmer" is simply always false. Linters such as ESLint's valid-typeof rule catch this.
A Rare Exception: document.all
In browsers, typeof document.all returns "undefined" even though document.all is an object. The specification keeps this exception so that very old scripts work. It is falsy as well. You will almost never meet it, but it shows that typeof reports a classification and can be overridden by the host environment. It is not a perfect window onto a value's type.
When typeof Is the Right Tool
typeof is reliable for the primitive types other than null, and for detecting callables:
| Question | Good check with typeof | Limitation |
|---|---|---|
| Is it a string? | `typeof x === "string"` | Misses `new String()` wrappers |
| Is it a number? | `typeof x === "number"` | Includes `NaN` and `Infinity` |
| Can I call it? | `typeof x === "function"` | None in practice |
| Does this global exist? | `typeof name !== "undefined"` | Throws in the temporal dead zone |
| Is it a plain object? | Not answerable | Arrays, dates, and `null` all say `"object"` |
For arrays, null, and specific built-in object kinds, you need other checks. The chapter "Checking Types Reliably" covers them.
Exercise
Predict the output of each line: typeof null, typeof [1, 2], typeof class {}, typeof new Boolean(false), typeof NaN, and typeof typeof 1n.
Show answer
"object", "object", "function", "object", "number", "string". null reports "object" because of the original type-tag bug. Arrays are non-callable objects. Classes are callable, so they report "function". new Boolean creates a wrapper object. NaN is a Number value. typeof always returns a string, so typeof of any typeof result is "string".
Exercise
A function guards with if (typeof config === "object") { return config.debug; }. Name a value that passes the guard and then throws, and rewrite the guard so it does not throw.
Show answer
null passes the guard because typeof null is "object", and reading null.debug throws a TypeError. A safe guard is if (typeof config === "object" && config !== null) { return config.debug; }. Optional chaining, config?.debug, also avoids the error.
Exercise
Why does typeof missingVar return "undefined" while typeof x throws when it appears just before let x = 1; in the same block?
Show answer
missingVar is not declared anywhere, so the reference cannot be resolved, and typeof handles an unresolvable reference by returning "undefined". x is declared with let, so its binding exists but is in the temporal dead zone until the declaration runs. Reading an uninitialized binding throws a ReferenceError, and typeof does not catch that case.