brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: ??= sets a default only when a value is null or undefined

Web-Development
~/tips/tip-javascript-nullish-assignment

options.duration ??= 100;

Assigns a default value only when the variable is null or undefined, keeping 0 and empty strings.

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 (??=)

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link