How to use nullish coalescing in JavaScript

· Category: JavaScript

Short answer

The ?? operator returns the right-hand operand only when the left-hand operand is null or undefined, unlike || which treats all falsy values as missing.

Steps

  1. Provide a default for nullish values: javascript const count = 0; const result = count ?? 10; // 0
  2. Contrast with logical OR: javascript const resultOr = count || 10; // 10 (wrong for 0)
  3. Chain defaults: javascript const port = config.port ?? process.env.PORT ?? 3000;
  4. Combine with optional chaining: javascript const name = user?.name ?? "Guest";

Tips

  • Use ?? for configuration values where 0, false, or "" are valid.
  • Parenthesize when mixing with && or || to avoid precedence errors.

Common issues

  • Mixing ?? with && or || without parentheses throws a syntax error in some older parsers.
  • Developers mistakenly use || for numeric defaults, causing 0 to be overwritten.