JavaScript's typeof Operator: Uses and Limitations

In JavaScript we use typeof to determine the type of a variable or value. Whilst it's very straightforward and commonly used, typeof does sometimes yield results that are not as intuitive as one might expect...
What is typeof?
typeof is a unary operator which returns a string indicating the type of the operand you've passed to it. It is often used to check the data type of a variable or value, especially when working with dynamic or unknown data.
typeof syntax
typeof operandoperand: The variable or value whose type we want to determine.
Using typeof
The typeof operator is straightforward to use, so here are a few examples:
console.log(typeof 'Hello'); //=> 'string'
console.log(typeof 42); //=> 'number'
console.log(typeof true); //=> 'boolean'
console.log(typeof undefined); //=> 'undefined'
console.log(typeof null); //=> 'object' (This is a known JavaScript quirk)
console.log(typeof {}); //=> 'object'
console.log(typeof function () {}); //=> 'function'Quirks and Limitations of typeof
You might have noticed in the example above that typeof null returns object. Whilst typeof is useful, it does have several limitations which can lead to misleading results.
Arrays and null Share a Result
Arrays are objects, but null is a primitive value. Both produce "object" when checked with typeof: the null result is a historical quirk retained for compatibility. Use Array.isArray(value) to detect an array and value === null to check for null directly.
console.log(typeof [1, 2, 3]); //=> 'object'
console.log(typeof null); //=> 'object'Functions are a Special Case
Functions, though objects in nature, are returned as 'function' by typeof. This is a special concession within JavaScript, as functions are first‑class objects with callable abilities.
Primitive Types and Object Instances
typeof does distinguish symbols: typeof Symbol() returns "symbol". It also returns "bigint" for a BigInt primitive. By contrast, new Map() and new Set() create objects, so both return "object". That result tells us their broad type, rather than which collection they implement.
Limited Use for User‑Defined Objects
For custom objects and classes, typeof will return 'object', making it unsuitable for more specific type checks.
Why Understanding typeof is Important
Despite some limitations, understanding and correctly using typeof is an important part of JavaScript development:
- It aids in debugging and validation of function arguments.
- It is useful in conditional statements where type‑checking is required.
- It helps in understanding and dealing with JavaScript's dynamic typing system.
Wrapping Up
JavaScript's typeof operator is a quick and easy way to check basic data types, but you should be aware of its limitations and quirks. For more complex type‑checking scenarios, other methods like Array.isArray(), instanceof, or even custom type‑checking functions may be more appropriate.