Перейти до основного вмісту
Frontend — це безкоштовний бонус CodeMentor AI; основний продукт — Python. Зареєструйся, щоб зберегти прогрес і відкрити всі 299 уроків фронтенду + 1,100+ уроків Python.Зареєструватись — безкоштовно
← ⚡ JavaScript & the browser·Модуль C5 · Урок 1
Завдання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
Теорія

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 вкладок
Живий перегляд
console output appears here…
← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.