Sari la conținutul principal
Frontend este un bonus gratuit pe CodeMentor AI — produsul principal este Python. Înregistrează-te pentru a-ți salva progresul și a debloca toate cele 299 de lecții Frontend + 1,100+ lecții Python.Înregistrează-te — gratuit
← ⚡ JavaScript & the browser·Modul C5 · Lecția 1
SarcinăWrite 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
Teorie

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 file
Previzualizare live
console output appears here…
← AnterioarăLecția următoare →

Primește un sfat Python sau web pe zi — prin email

Scurt, scris de mână, fără spam. Dezabonare cu un click.