typeof Basics
JavaScript · Reference cheat sheet
typeof Basics
JavaScript · Reference cheat sheet
📋 Overview
typeof is an operator that returns a string describing a value’s type tag. It is useful for quick checks while learning, with a few famous quirks to memorize.
🔧 Core concepts
| Expression | Typical result |
|---|---|
typeof "hi" | "string" |
typeof 42 | "number" |
typeof 42n | "bigint" |
typeof true | "boolean" |
typeof undefined | "undefined" |
typeof Symbol() | "symbol" |
typeof \{\} / [] / null | "object" (see pitfalls) |
typeof function () \{\} | "function" |
typeof never throws on an undeclared variable in older patterns like typeof x — it yields "undefined". Prefer declared variables anyway.
💡 Examples
Primitives:
console.log(typeof "hello"); // string
console.log(typeof 3.14); // number
console.log(typeof true); // boolean
console.log(typeof undefined); // undefinedObjects and functions:
console.log(typeof { a: 1 }); // object
console.log(typeof [1, 2]); // object
console.log(typeof null); // object ← historical bug
console.log(typeof (() => 1)); // functionGuarding before use:
function double(n) {
if (typeof n !== "number" || Number.isNaN(n)) {
throw new TypeError("n must be a number");
}
return n * 2;
}
console.log(double(21));Optional value check:
let title;
console.log(typeof title); // undefined
title = "Docs";
console.log(typeof title); // string⚠️ Pitfalls
typeof null === "object"— check null withvalue === null.- Arrays are
"object"— useArray.isArray(x). typeof NaNis"number".- For class instances, prefer
instanceofor brand checks overtypeof.