Naar hoofdinhoud
Frontend is een gratis bonus op CodeMentor AI — het hoofdproduct is Python. Registreer om je voortgang op te slaan en alle 299 Frontend-lessen + 1,100+ Python-lessen te ontgrendelen.Meld je aan — gratis
← ⚡ JavaScript & the browser·Module C5 · Les 1
OpdrachtWrite 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
Theorie

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…
← VorigeVolgende les →

Eén Python- of web-tip per dag — per e-mail

Kort, met de hand geschreven, geen spam. Met één klik afmelden.