Przejdź do treści głównej
Frontend to darmowy bonus w CodeMentor AI — głównym produktem jest Python. Zarejestruj się, aby zapisać postępy i odblokować wszystkie 299 lekcji Frontend + 1,100+ lekcji Python.Zarejestruj się — za darmo
← ⚡ JavaScript & the browser·Moduł C1 · Lekcja 8
ZadanieDefine const a = 0, const b = null, const c = ''. Log a ?? 'fallback' (expect 0), b ?? 'fallback' (expect 'fallback'), and c || 'fallback' (expect 'fallback').

Warunki warunkowe + fałszywa odpowiedź

75 XP7 minFREE
Teoria

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
Podgląd na żywo
console output appears here…
← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.