Member-only story
Understanding Nullish Coalescing Assignment (??=) in JavaScript
The Nullish Coalescing Assignment (??=
) is a relatively new operator in JavaScript, introduced in ES2021. It provides a shorthand way to assign a value to a variable only if the variable is null
or undefined
. This is particularly useful when you want to avoid overwriting values that are not nullish but could be falsy, such as 0
, false
, or an empty string (''
).
Not a Medium member? Read this article here
In this article, we’ll break down how ??=
works, how it differs from other assignment operators, and when it should be used.
What is Nullish Coalescing?
Before diving into the assignment operator, it’s important to understand the concept of nullish coalescing. The Nullish Coalescing Operator (??
) allows you to return the right-hand operand if the left-hand operand is null
or undefined
. If the left-hand operand is any other value, including false
, 0
, or ''
, the left-hand operand is returned.
const value = null ?? 'default';
console.log(value); // 'default'
const value2 = 0 ?? 'default';
console.log(value2); // 0 (because 0 is not null or undefined)