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:
undefined: Returns"undefined"for unassigned variables or values explicitly set toundefined.boolean: Returns"boolean"fortrueandfalse.number: Returns"number"for all numerical values, including integers, floating-point numbers,Infinity,-Infinity, andNaN(Not-a-Number).bigint: Returns"bigint"for arbitrary-precision integers (e.g.,10n).string: Returns"string"for sequences of characters enclosed in single quotes, double quotes, or template literals.symbol: Returns"symbol"for unique identifier tokens created usingSymbol().
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:
- Plain Objects: Standard key-value pairs (e.g.,
{ a: 1 }) return"object". - Arrays: Arrays (e.g.,
[1, 2, 3]) return"object". To verify an array specifically, useArray.isArray(). - Built-in Objects: Standard instances like
Date,RegExp,Map,Set,Promise, and wrapper objects created withnew Object()return"object". - Functions: Functions, generator functions, and
classes return
"function". In JavaScript, functions are technically callable objects, buttypeofprovides a dedicated"function"string for them.
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]").