Prejsť na hlavný obsah
Frontend je bezplatný bonus na CodeMentor AI — hlavným produktom je Python. Zaregistruj sa a ulož si pokrok a odomkni všetkých 299 Frontend lekcií + 1,100+ Python lekcií.Zaregistruj sa — zdarma
← ⚡ JavaScript & the browser·Modul C1 · Lekcia 8
ÚlohaDefine const a = 0, const b = null, const c = ''. Log a ?? 'fallback' (expect 0), b ?? 'fallback' (expect 'fallback'), and c || 'fallback' (expect 'fallback').

Podmienečné + falošný gotcha

75 XP7 minFREE
Teória

The seven falsy values

In JavaScript, these all evaluate to false in an if:

false
0
0n        (BigInt zero)
""        (empty string)
null
undefined
NaN

Everything else — including "0", "false", [], {}, -1 — is truthy. This is the source of half of all "weird JS" jokes.

Two operators worth knowing cold

const a = value ?? "default";   // "nullish coalescing"
const b = value || "default";   // logical OR

?? returns value unless it's null or undefined. So:

0 ?? "default"        // 0   (zero is a real value)
0 || "default"        // "default"  (zero is falsy)

?? saved a thousand bugs. Reach for it when you're providing a default and zero / empty string is meaningful.

Optional chaining

const city = user?.address?.city ?? "unknown";

If any link is null or undefined, the whole expression short-circuits to undefined (which ?? then catches). Replaces five lines of if (user && user.address) checks with one chain.

A real-world example

function welcome(user) {
  const name = user?.name ?? "stranger";
  return `hi, ${name}`;
}

welcome();                  // "hi, stranger"
welcome({});                // "hi, stranger"
welcome({ name: "" });      // "hi, " — empty string is NOT nullish
welcome({ name: 0 });       // "hi, 0" — same

The empty-string + zero cases bite — if you wanted to default those, use || instead of ??. Picking the right operator is a small decision that compounds across a codebase.

2 karty
Živý náhľad
console output appears here…
← PredchádzajúcaĎalšia lekcia →

Jeden tip k Pythonu alebo webu denne — e-mailom

Krátke, ručne písané, žiadny spam. Odhlásiť jedným klikom.