Zum Hauptinhalt springen
Frontend ist ein kostenloser Bonus bei CodeMentor AI — das Hauptprodukt ist Python. Registriere dich, um deinen Fortschritt zu speichern und alle 299 Frontend-Lektionen + 1,100+ Python-Lektionen freizuschalten.Registrieren — kostenlos
← ⚡ JavaScript & the browser·Modul C5 · Lektion 1
AufgabeWrite 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-Vorschau
console output appears here…
← ZurückNächste Lektion →

Bekomme einen Python- oder Web-Tipp pro Tag — per E-Mail

Kurz, handgeschrieben, kein Spam. Abmelden mit einem Klick.