typeof OperatorIn JavaScript, the typeof operator returns a string indicating the data type of the unevaluated operand. It is an incredibly useful tool for type-checking and debugging.
typeof operand // or typeof(operand)
typeof Return ValuesThe typeof operator can return one of the following strings:
| Data Type | String Returned by typeof |
|---|---|
| String | "string" |
| Number | "number" |
| BigInt | "bigint" |
| Boolean | "boolean" |
| Symbol | "symbol" |
| Undefined | "undefined" |
| Object | "object" |
| Function | "function" |
console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof 123n); // "bigint"
console.log(typeof Symbol('id')); // "symbol"
typeof Operator and ObjectsIt's important to note that typeof returns "object" for all object types, including arrays, dates, and regular expressions. It does not differentiate between them.
console.log(typeof {name: "John"}); // "object"
console.log(typeof [1, 2, 3]); // "object"
console.log(typeof new Date()); // "object"
typeof null BugOne of the most famous quirks in JavaScript is that typeof null returns "object".
Historical Bug: This is a well-known bug from the earliest days of JavaScript. For backward compatibility, it has never been fixed. You should remember that null is a primitive value, not an object, despite what typeof says.
let data = null; console.log(typeof data); // "object"
To correctly check if a value is an object (and not null), you should use:
value !== null && typeof value === 'object'
What does `typeof [1, 2, 3]` return?