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
1// Numbers (regular and NaN)
2typeof 42; // "number"
3typeof 3.14; // "number"
4typeof NaN; // "number"
5
6// Strings
7typeof 'hello'; // "string"
8typeof ''; // "string"
9
10// Booleans
11typeof true; // "boolean"
12typeof false; // "boolean"
13
14// Undefined
15typeof undefined; // "undefined"
16
17// Objects and null
18typeof {}; // "object"
19typeof null; // "object" (this is a known JavaScript quirk)
20typeof []; // "object" (arrays are objects in JavaScript)
21
22// Functions
23typeof function () {}; // "function"
24
25// Symbol (added in ES6)
26typeof Symbol(); // "symbol"
27
28// BigInt (added in ES2020)
29typeof 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
1if (typeof someVariable !== 'undefined') {
2 // safe to use someVariable
3}

Finished reading?

Mark this topic as solved to track your progress.