Curriculum Series

What does typeof operator do?

What does typeof operator do?

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"
// Strings
typeof 'hello'; // "string"
typeof ''; // "string"
// Booleans
typeof true; // "boolean"
typeof false; // "boolean"
// Undefined
typeof undefined; // "undefined"
// Objects and null
typeof {}; // "object"
typeof null; // "object" (this is a known JavaScript quirk)
typeof []; // "object" (arrays are objects in JavaScript)
// Functions
typeof 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 null returns "object", which is a historical bug in JavaScript
  • Arrays are considered objects, so typeof [] returns "object"
  • You can use typeof on 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
}

Finished reading?

Mark this topic as solved to track your progress.