JavaScript Nullish Coalescing Operator (??): A Guide to Handling Null and Undefined

3 min read .

The Nullish Coalescing Operator (??) in JavaScript is a useful tool for dealing with null and undefined values. This operator provides a cleaner, more intuitive way to assign default values, making your code easier to read and maintain.

What is the Nullish Coalescing Operator (??)?

The Nullish Coalescing Operator (??) is a logical operator that returns the right-hand operand when the left-hand operand is null or undefined. If the left-hand operand has any other value (including 0, false, or an empty string), it returns that value instead.

Syntax:

const result = operand1 ?? operand2;
  • operand1: The value to be checked for null or undefined.
  • operand2: The fallback value if operand1 is null or undefined.

Why Use the Nullish Coalescing Operator?

  • Cleaner Code: Provides a straightforward syntax for handling null and undefined.
  • Avoids Unintended Fallbacks: Unlike the logical OR (||) operator, ?? does not treat falsy values like 0, false, or '' as null or undefined, ensuring that meaningful values are not overwritten.
  • Better Defaults: Allows precise control over when to assign default values, enhancing code reliability.

How to Use the Nullish Coalescing Operator

  1. Basic Usage

The operator checks whether the left-hand operand is null or undefined and returns the right-hand operand only if it is.

let username = null;
let defaultName = 'Guest';

let name = username ?? defaultName;
console.log(name); // Output: Guest
  1. Difference Between ?? and ||

The || operator returns the right operand if the left operand is any falsy value (null, undefined, 0, false, '', etc.). In contrast, ?? only checks for null or undefined.

let count = 0;

let resultOR = count || 10; // Uses default because 0 is falsy
console.log(resultOR); // Output: 10

let resultNullish = count ?? 10; // Does not use default because 0 is not null or undefined
console.log(resultNullish); // Output: 0
  1. Using ?? in Function Defaults

?? can provide more accurate default values in function arguments, especially when distinguishing between 0, false, and undefined.

function getDiscountedPrice(price, discount) {
  discount = discount ?? 0; // Only assigns 0 if discount is null or undefined
  return price - (price * discount);
}

console.log(getDiscountedPrice(100, 0)); // Output: 100 (0 discount applied)
console.log(getDiscountedPrice(100, null)); // Output: 100 (no discount applied)
  1. Chaining ?? for Multiple Fallbacks

You can chain multiple ?? operators to provide fallback values in sequence until a non-nullish value is found.

let configValue = undefined;
let userValue = null;
let defaultValue = 'Default';

let finalValue = configValue ?? userValue ?? defaultValue;
console.log(finalValue); // Output: Default
  1. Using ?? with Optional Chaining

The Nullish Coalescing Operator pairs well with Optional Chaining (?.) to safely access deeply nested properties.

let user = {
  profile: {
    name: 'Alice',
  },
};

let bio = user.profile?.bio ?? 'Bio not available';
console.log(bio); // Output: Bio not available

Common Pitfalls with the Nullish Coalescing Operator

  • ?? Requires Parentheses When Combined with && or ||: Mixing ?? with && or || operators without parentheses leads to syntax errors due to precedence rules.

    // Correct Usage
    let value = (0 || undefined) ?? 'fallback'; // Uses parentheses
    console.log(value); // Output: fallback
    
    // Incorrect Usage (will throw an error)
    // let value = 0 || undefined ?? 'fallback';
    

Browser Compatibility

The Nullish Coalescing Operator is widely supported in modern browsers, including Chrome (version 80+), Firefox (version 72+), Safari (version 13.1+), and Edge (version 80+). It is not supported in Internet Explorer, so caution is advised if targeting legacy systems.

Conclusion

The Nullish Coalescing Operator (??) is a powerful addition to JavaScript, simplifying code that deals with null or undefined values. By distinguishing between nullish and other falsy values, ?? provides a precise, reliable way to assign defaults and improve code readability.

See Also

chevron-up