JavaScript typeof Operator – How to Check Data Types
In JavaScript, the typeof
operator is used to determine the type of a given variable or value. It helps developers identify what kind of data they are working with—such as a string, number, boolean, object, or function—making it a key part of debugging and writing reliable code.
Syntax
typeof operand
// or
typeof(operand)
Example:
typeof "Hello"; // "string"
typeof 123; // "number"
typeof true; // "boolean"
Common Return Values of typeof
Type | Example | typeof Result | Description |
---|---|---|---|
String | "JavaScript" | "string" | Sequence of characters. |
Number | 42 , 3.14 | "number" | Integer or floating-point number. |
BigInt | 123n | "bigint" | For arbitrarily large integers. |
Boolean | true , false | "boolean" | Logical true/false value. |
Undefined | undefined | "undefined" | Variable declared but not assigned a value. |
Object | {} , [1,2,3] , null | "object" | Collections, arrays, or null (special case). |
Function | function() {} | "function" | Any callable object or function. |
Symbol | Symbol('id') | "symbol" | Unique and immutable primitive value. |
Examples of typeof in Action
Primitive Data Types
console.log(typeof "John"); // "string"
console.log(typeof 25); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof 123n); // "bigint"
console.log(typeof Symbol("id")); // "symbol"
Non-Primitive (Reference) Data Types
console.log(typeof { name: "Alice" }); // "object"
console.log(typeof [1, 2, 3]); // "object" (arrays are also objects)
console.log(typeof null); // "object" (this is a long-standing JavaScript bug)
console.log(typeof function(){}); // "function"
Special Cases and Gotchas
typeof null
→ "object"
This is a well-known JavaScript quirk from its early implementation.
Even though null
is a primitive type, typeof null
incorrectly returns "object"
.
console.log(typeof null); // "object"
Arrays
typeof
returns "object"
for arrays too, even though they are special objects:
console.log(typeof [1,2,3]); // "object"
To specifically check for an array, use:
Array.isArray([1,2,3]); // true
NaN (Not a Number)
console.log(typeof NaN); // "number"
typeof with undeclared variables
Unlike most operations, using typeof
on an undeclared variable does not throw an error — it safely returns "undefined"
:
console.log(typeof undeclaredVar); // "undefined"