I used to write options.speed = options.speed || 25 for defaults, and it has a bug I keep seeing: a speed of 0 gets replaced by 25. The ??= operator fixes that.
x ??= y assigns y to x only when x is null or undefined. If x already has a value, nothing happens and y is not even evaluated:
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({ duration: null }); // { duration: 100, speed: 25 }
config({ speed: 0 }); // { speed: 0, duration: 100 }
The last line is the point. With ||= the zero would be treated as missing and overwritten, and the same goes for an empty string or false:
let a = 0;
a ||= 10; // a is 10
a = 0;
a ??= 10; // a stays 0
It is also handy for lazy setup, such as a cache that you create the first time it is needed:
cache.users ??= new Map();
The right side only runs when needed, so an expensive call there is skipped when the value already exists.
Caveats: ??= does not treat an empty string as missing, which is sometimes what you want and sometimes not, for example with a form field. Pick ||= when empty should count as missing. Also, it is an assignment, so it fails on a frozen object just like a normal write would.
It works in all major browsers since September 2020.
Further reading: MDN: Nullish coalescing assignment (??=)