What does typeof operator do?
JavaScript
typeof operator
The typeof operator in JavaScript returns a string indicating the data type of an operand. Let me break down how it works with different types:
javascript
// 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" - You can use
typeofon undeclared variables without causing an error, it will return "undefined"
The operator is particularly useful for type checking and defensive programming, like checking if a variable exists before using it:
javascript
if (typeof someVariable !== 'undefined') {// safe to use someVariable}