Saltar al contenido principal
Frontend es un bono gratis en CodeMentor AI — el producto principal es Python. Regístrate para guardar tu progreso y desbloquear las 299 lecciones de Frontend + 1,100+ lecciones de Python.Regístrate — gratis
← ⚡ JavaScript & the browser·Módulo C1 · Lección 8
TareaDefine const a = 0, const b = null, const c = ''. Log a ?? 'fallback' (expect 0), b ?? 'fallback' (expect 'fallback'), and c || 'fallback' (expect 'fallback').

Condicionales + el falso truco

75 XP7 minFREE
Teoría

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 pestañas
Vista en vivo
console output appears here…
← AnteriorSiguiente lección →

Recibe un consejo de Python o web al día — por email

Corto, escrito a mano, sin spam. Anula la suscripción en un clic.