typeof: Inspecting Value Types and Edge CasesThe JavaScript typeof operator returns a lowercase string describing the data type of an expression or variable. It helps you guard function inputs and check whether a global API exists without throwing a ReferenceError.
typeof Return ValuesKnow these eight possible string results from typeof:
"string", "number", "boolean", "bigint", "symbol", "undefined": Returned for those six primitive types."function": Returned for functions and ES6 class constructors."object": Returned for plain objects, arrays, Date, RegExp, Map, Set, and notoriously null.Because typeof null returns "object" and typeof [1, 2] also returns "object", pair typeof with explicit === null and Array.isArray() checks.
function describeValue(value) {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
if (typeof value === "number" && Number.isNaN(value)) return "NaN";
return typeof value;
}
console.log(describeValue(null)); // "null"
console.log(describeValue([1, 2, 3])); // "array"
console.log(describeValue(Number("abc"))); // "NaN"
console.log(describeValue(() => {})); // "function"
console.log(describeValue(42n)); // "bigint"
typeof val === "object" without excluding null: Passing null passes that check and crashes when you read val.name. Always write val !== null && typeof val === "object".typeof to tell arrays apart from objects: typeof [] is "object"; always call Array.isArray(val).typeof on an uninitialized let variable before its line: Calling typeof x on an undeclared global returns "undefined", yet calling typeof x inside a block above let x = 1 throws a ReferenceError due to the Temporal Dead Zone.typeof null return "object" in JavaScript?It is a famous backward-compatibility bug from the very first 1995 JavaScript engine, where both objects and null shared a zero type tag. Changing it today would break millions of legacy websites.
typeof NaN return?typeof NaN returns "number" because NaN belongs to the IEEE 754 floating-point number specification. Check Number.isNaN(val) to catch NaN.
typeof return for an ES6 class?Classes in JavaScript are syntactic sugar over constructor functions, so typeof MyClass returns "function".
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.