JavaScript `??=`: Nullish Coalescing Assignment
1
min read .
Updated on
The nullish coalescing assignment operator, ??=, assigns a value only when the current left-hand value is null or undefined.
let name = null;
name ??= 'Guest';
console.log(name); // Guest
Function Defaults
function greet(user) {
user ??= 'Stranger';
console.log(`Hello, ${user}!`);
}A default parameter may be even clearer when only undefined needs a fallback:
function greet(user = 'Stranger') {
console.log(`Hello, ${user}!`);
}Object Properties
const settings = { theme: undefined, fontSize: 16 };
settings.theme ??= 'light';??= vs. ||=
||= treats every falsy value as missing. ??= preserves 0, false, and '':
let count = 0;
count ??= 10;
console.log(count); // 0
Conclusion
Use ??= when only null or undefined should trigger a default assignment. It is a compact way to initialize optional values without overwriting meaningful falsy data.