Understanding Nullish Coalescing Assignment (??=) in JavaScript

Understanding Nullish Coalescing Assignment (??=) in JavaScript

When developing JavaScript applications, it’s common to assign values to properties only if they don’t already exist or if they are null/undefined. Traditionally, developers would use an if statement for this task, like:

if (!obj.property) {
  obj.property = value;
}

While this works, there's a more concise and modern approach—Nullish Coalescing Assignment (??=). This operator allows you to simplify the code by eliminating the need for an if statement.

How Does It Work?

With nullish coalescing assignment, you can assign a value to a variable only if its current value is either null or undefined (also known as "nullish" values).

For example:

codeobj.speed ??= 25;

This statement checks if obj.speed is null or undefined. If it is, it assigns the value 25 to obj.speed. If obj.speed already has a valid value (like 50), it remains unchanged.

Let’s look at another example:

let a = { speed: null, duration: 50 };

a.speed ??= 25;    // a.speed becomes 25
a.duration ??= 100; // a.duration remains 50 (it’s already defined)

In this case:

  • speed gets assigned 25 because its value was null.

  • duration stays 50 because it already had a defined value.

Why Use Nullish Coalescing Assignment?

  • Cleaner code: It replaces if statements, making your code more readable.

  • Handles only nullish values: Unlike the || operator, which treats 0, '' (empty strings), and false as falsy values, ??= only triggers for null and undefined.

Clarification: How It Differs from ||

A common approach is using || to assign default values, like:

javascriptCopy codestr || "" // assigns empty string if str is falsy (e.g. "", 0, false)

However, the || operator assigns the default value for any falsy value. This can lead to unintended results if 0 or "" are valid values. With ??, you specifically target only null or undefined:

javascriptCopy codestr ?? "" // only assigns if str is null or undefined

Additionally, there’s a ||= operator that works similarly to ??=, but it assigns a value if the variable is falsy (including 0, '', etc.).

Final Thoughts

The nullish coalescing assignment (??=) is a great tool for simplifying conditional assignments in JavaScript. It's especially useful in modern development, helping developers write cleaner and more efficient code.