Прескочи на главни садржај
Frontend je besplatan bonus na CodeMentor AI — glavni proizvod je Python. Registruj se da sačuvaš napredak i otključaš svih 299 Frontend lekcija + 1,100+ Python lekcija.Региструј се — бесплатно
← ⚡ JavaScript & the browser·Модул C1 · Лекција 8
ЗадатакDefine const a = 0, const b = null, const c = ''. Log a ?? 'fallback' (expect 0), b ?? 'fallback' (expect 'fallback'), and c || 'fallback' (expect 'fallback').

Услови + лажна ствар

75 XP7 minFREE
Теорија

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 картице
Живи преглед
console output appears here…
← ПретходнаСледећа лекција →

Један савет за Python или веб дневно — на имејл

Кратко, ручно писано, без спама. Одјава у једном клику.