Yeda AI Tips · #115

Español

Use ?? For Defaults, Not ||

This JavaScript default-value bug is probably in your codebase right now. config.port || 3000 looks perfectly reasonable — and it silently rewrites a port of 0 to 3000, an empty prefix to your fallback string, and an explicit false to true. The fix is two characters: ??.

The bug: || tests truthiness, not presence

x || y returns y whenever x is falsy. JavaScript has six falsy values: false, 0, "" (empty string), null, undefined, and NaN. Four of those are perfectly valid configuration values:

const port    = config.port    || 3000;   // 0      -> 3000  (bug)
const prefix  = config.prefix  || "app";  // ""     -> "app" (bug)
const retries = config.retries || 5;      // 0      -> 5     (bug)
const debug   = config.debug   || true;   // false  -> true  (bug!)

The user set those values. || throws them away because it can't tell "absent" from "falsy". port: 0 is a real request — "give me a random free port" in Node's server.listen(0) — and debug: false is the single most common way to turn something off.

The fix: ?? tests nullish, not falsy

The nullish coalescing operator (??, ES2020) falls back only when the left side is null or undefined:

const port    = config.port    ?? 3000;   // 0      stays 0
const prefix  = config.prefix  ?? "app";  // ""     stays ""
const retries = config.retries ?? 5;      // 0      stays 0
const debug   = config.debug   ?? true;   // false  stays false

Absent key? config.port is undefined, you get 3000. Explicit null? You get 3000. Anything else — including every falsy value the user meant — survives.

Rules of thumb

Input valuex || 3000x ?? 3000
undefined30003000
null30003000
030000
""fallback""
falsefallbackfalse
NaNfallbackNaN
808080808080

Keep || only when you genuinely want to treat all falsy values as missing — e.g. normalizing user text where "" should become a placeholder. For config, options objects, and API responses, default with ??.

Power-user corner

Resources

Building an AI feature? Yeda AI designs, audits, and ships production LLM systems.

Talk to us · Read the blog