javascript / intermediate
Snippet
Efficient Property Initialization with Nullish Assignment
The nullish coalescing assignment operator (??=) only assigns a value if the variable is null or undefined, which is safer than using || for falsy values like 0 or empty strings.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
function setupConfig(options) {options.timeout ??= 3000;options.retries ??= 5;options.debug ??= false;return options;}// Example: setupConfig({ timeout: 0 })// timeout remains 0 because it's not null or undefined.
Breakdown
1
options.timeout ??= 3000;
Assigns 3000 only if timeout is nullish (null or undefined).
2
// timeout remains 0
Demonstrates that falsy but valid values (like 0) are preserved.