Lesson 10 +10 XP

The typeof Operator

The typeof Operator

typeof tells you what type a value is. It is extremely useful for debugging.

Basic usage

typeof "Hello";  // "string"
typeof 3.14;     // "number"
typeof true;     // "boolean"
typeof undefined; // "undefined"
typeof null;     // "object" (a famous quirk)

Objects, arrays, functions

typeof { name: "Ada" }; // "object"
typeof [1, 2, 3];       // "object" (arrays are objects!)
typeof function () {};  // "function"

The null quirk

typeof null returns "object", even though null is not really an object. This is an old bug kept for compatibility. To check for null, compare directly:

if (value === null) { ... }

typeof in real code

Use typeof to avoid errors when a value might be undefined:

if (typeof someFunction === "function") {
  someFunction();
}

typeof is an operator

typeof is an operator, not a function, but it can be written with or without parentheses.

TL;DR

  • typeof returns a value's type as a string.
  • Arrays return "object" because they are objects.
  • typeof null returns "object" (a known quirk).
  • Use it to safely check what a value is.