Skip to main content
Frontend is a free bonus on CodeMentor AI — the main product is Python. Register to save your progress and unlock all 290 Frontend lessons + 1,000+ Python lessons.Sign up — free
JavaScript & the browser·Module C5 · Lesson 1
TaskWrite a function describe(x) that returns "<value>: <type>". Log describe(7), describe("hi"), describe(true), describe(undefined), describe(null), describe([]), describe(() => 1) on separate lines.

typeof — the runtime type guard

75 XP6 minFREE
Theory

What typeof returns

typeof x returns a string describing x's primitive type. It's the only operator in JS that won't throw if x is undeclared — typeof unknownThing === "undefined" is safe.

typeof 7;          // "number"
typeof "hi";       // "string"
typeof true;       // "boolean"
typeof undefined;  // "undefined"
typeof null;       // "object"   ← famous JS bug, kept for back-compat
typeof [];         // "object"   ← arrays are objects (lesson C5-03 fixes)
typeof (() => 1);  // "function"
typeof Symbol();   // "symbol"

Why this matters without TypeScript

Without a compiler checking types for you, typeof is your runtime guard. You'll write this pattern dozens of times:

function double(x) {
  if (typeof x !== "number") {
    throw new TypeError("double expects a number, got " + typeof x);
  }
  return x * 2;
}

Narrow-then-act is everywhere in production JS. Lesson C5-02 chains it for branching.

2 tabs
Live preview
console output appears here…
PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.