typeof operator
The typeof operator returns a string naming the type of its operand:
// Numbers (regular and NaN)typeof 42; // "number"typeof 3.14; // "number"typeof NaN; // "number"// Stringstypeof 'hello'; // "string"typeof ''; // "string"// Booleanstypeof true; // "boolean"typeof false; // "boolean"// Undefinedtypeof undefined; // "undefined"// Objects and nulltypeof {}; // "object"typeof null; // "object" (this is a known JavaScript quirk)typeof []; // "object" (arrays are objects in JavaScript)// Functionstypeof function () {}; // "function"// Symbol (added in ES6)typeof Symbol(); // "symbol"// BigInt (added in ES2020)typeof 42n; // "bigint"There are a few important gotchas to be aware of:
- typeof
nullreturns "object", which is a historical bug in JavaScript - Arrays are considered objects, so
typeof []returns "object" typeofon an undeclared variable returns"undefined"without throwing. Aletorconstvariable in its temporal dead zone still throws aReferenceError.
The operator is particularly useful for type checking and defensive programming, like checking if a variable exists before using it:
if (typeof someVariable !== 'undefined') { // safe to use someVariable}