The typeof operator is the most common way to check the data type of a
JavaScript variable. It returns a string that tells you what kind of data the value is.
Here is a complete list of what typeof returns for different values:
| Data Type | Return Value |
|---|---|
| String | "string" |
| Number | "number" |
| BigInt | "bigint" |
| Boolean | "boolean" |
| Undefined | "undefined" |
| Function | "function" |
| Object | "object" |
| Null | "object" (The "null bug") |
JavaScript has two categories of data. typeof can easily identify primitives
but treats most complex data as objects.
These are simple values: string, number, boolean, undefined, null.
typeof "Mim" // "string"
typeof 25 // "number"
typeof true // "boolean"
These are objects and functions. Notice that arrays are technically objects.
typeof {name:'Mim'} // "object"
typeof [1, 2, 3] // "object" (Arrays are objects!)
typeof new Date() // "object"
Since typeof [] returns "object", you need a different way to
check if a variable is an array:
let colors = ["Red", "Green"];
// Method 1: Array.isArray()
console.log(Array.isArray(colors)); // true
// Method 2: instanceof
console.log(colors instanceof Array); // true
In JavaScript, typeof null returns 'object'. This is a famous bug from the very first version of JavaScript. It remains in the language today because fixing it would break millions of websites that rely on this behavior.
null, use a direct
comparison: if (myValue === null).
The constructor property returns the constructor function for all JavaScript variables. This is a very reliable way to identify technical types:
"Mim".constructor // returns function String()
(3.14).constructor // returns function Number()
[1,2,3].constructor // returns function Array()
{name:'Mim'}.constructor // returns function Object()
typeof returns the data type as a string"object" for both arrays and nullArray.isArray()constructor property is a more specific way to find
the data type