typeof: Type Inspection & Operating QuirksThe typeof unary operator returns a string indicating the type of the unevaluated operand. While reliable for primitives, typeof has historical quirks when inspecting null, arrays, and functions.
typeof Return Values Matrixflowchart TD
TypeOf["typeof operand"] --> Prim["Primitives"]
TypeOf --> Ref["Reference Objects"]
Prim --> PStr["String -> 'string'"]
Prim --> PNum["Number -> 'number'"]
Prim --> PBool["Boolean -> 'boolean'"]
Prim --> PBig["BigInt -> 'bigint'"]
Prim --> PSym["Symbol -> 'symbol'"]
Prim --> PUnd["Undefined -> 'undefined'"]
Prim --> PNull["null -> 'object' (HISTORICAL QUIRK!)"]
Ref --> RFunc["Function -> 'function'"]
Ref --> RArr["Array / Date / Object -> 'object'"]
typeof Evaluation Table| Operand Value | typeof Return Value |
Category / Note |
|---|---|---|
"Hello" |
"string" |
Primitive String |
42 / NaN |
"number" |
Primitive Number (NaN is a number type!) |
true |
"boolean" |
Primitive Boolean |
100n |
"bigint" |
Primitive BigInt |
Symbol("id") |
"symbol" |
Primitive Symbol |
undefined |
"undefined" |
Primitive Undefined |
null |
"object" |
Historical JS Engine Bug (1995) |
() => {} |
"function" |
Special Callable Object |
[1, 2] |
"object" |
Array (Use Array.isArray()) |
{ a: 1 } |
"object" |
Plain Object |
// Demonstrating typeof inspections, quirks, and reliable type check functions
// 1. Primitive and Function typeof checks
console.log(`typeof "Text": ${typeof "Text"}`); // "string"
console.log(`typeof 42: ${typeof 42}`); // "number"
console.log(`typeof NaN: ${typeof NaN}`); // "number" (Quirk!)
console.log(`typeof (() => {}): ${typeof (() => {})}`); // "function"
// 2. The Null and Array Quirks
console.log(`typeof null: ${typeof null}`); // "object" (Quirk!)
console.log(`typeof []: ${typeof []}`); // "object"
// 3. Reliable Robust Type Checker Function
function getExactType(value) {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;
}
console.log(`Exact Type null: ${getExactType(null)}`); // "null"
console.log(`Exact Type []: ${getExactType([])}`); // "array"
console.log(`Exact Type 10: ${getExactType(10)}`); // "number"
typeof to Check for null: typeof null === "object" evaluates to true. Always check for null using val === null.typeof for Arrays: typeof [] returns "object". Use Array.isArray(val).typeof undeclaredVar returns "undefined" without throwing a ReferenceError, making it safe for environment checks.Write a function isFunction(val) using typeof that returns true if val is a callable 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.