Modern Replacement for OR

The ?? (Nullish Coalescing) operator solves one specific problem of the || operator.

What's the difference?

  • || considers falsy: 0, "", false, null, undefined.
  • ?? considers " empty " ONLY: null and undefined.

Real-life Example

Imagine you are adjusting the volume in a media player:

let volume = 0; // The user muted the sound

alert(volume || 50); // 50 (ERROR! The user wanted 0, but got 50)
alert(volume ?? 50); // 0 (CORRECT! 0 is not null, so keep it)
Important

?? is perfect for situations where 0 or an empty string "" are normal valid data, not an error.

Warning

For safety reasons, JS forbids using ?? on the same line with && or || without parentheses. It will throw a syntax error.