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
1// Numbers (regular and NaN)2typeof 42; // "number"3typeof 3.14; // "number"4typeof NaN; // "number"56// Strings7typeof 'hello'; // "string"8typeof ''; // "string"910// Booleans11typeof true; // "boolean"12typeof false; // "boolean"1314// Undefined15typeof undefined; // "undefined"1617// Objects and null18typeof {}; // "object"19typeof null; // "object" (this is a known JavaScript quirk)20typeof []; // "object" (arrays are objects in JavaScript)2122// Functions23typeof function () {}; // "function"2425// Symbol (added in ES6)26typeof Symbol(); // "symbol"2728// BigInt (added in ES2020)29typeof 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
1if (typeof someVariable !== 'undefined') {2 // safe to use someVariable3}