JavaScript
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}
Related JavaScript interview topics
Continue with nearby questions from the same topic cluster.
What are the different types of errors in JavaScript?How does the this keyword work in JavaScript?What are the key differences between var, let, and const in JavaScript?What are the different ways to create objects in JavaScript?How do you convert a string to a number in JavaScript?What is hoisting in JavaScript?