JavaScript typeof Operator Explained

The JavaScript typeof operator evaluates an operand and returns a string indicating its data type. While it is an essential tool for basic type checking, its behavior varies significantly across primitive values, standard objects, functions, and historical language quirks. This guide details exactly how typeof classifies every fundamental data type and structural entity in JavaScript.

Primitive Data Types

Primitives are immutable values that are not objects and have no methods. The typeof operator identifies most primitive types intuitively:

The null Quirk

The primitive value null returns "object" instead of "null". This behavior is a well-known legacy bug originating from the first implementation of JavaScript, where values were represented using type tags, and null shared the zero tag assigned to objects. Because fixing it would break existing web infrastructure, null continues to return "object".

Objects and Complex Structures

For non-primitive data types, typeof behaves as follows:

Best Practices for Accurate Type Checking

Because typeof returns "object" for objects, arrays, built-in instances, and null, it cannot reliably distinguish between specific object structures.

For accurate type discrimination: * Use strict equality (value === null) to check for null. * Use Array.isArray(value) to check for arrays. * Use the instanceof operator to check if an object is an instance of a specific constructor (e.g., value instanceof Date). * Use Object.prototype.toString.call(value) to get a definitive, unambiguous internal type tag (e.g., "[object Array]", "[object Null]").