A snippet of Javascript code, showing the difference between the nullish coalescing and logical OR operators.

Writing Cleaner JavaScript with Nullish Coalescing: A Developer's Guide

by

Introduction

JavaScript has been continuously evolving, introducing new features that enhance developers’ productivity and improve code readability. One such feature is nullish coalescing, introduced in ECMAScript 2020, which addresses a common challenge faced by developers when dealing with null or undefined values. In this blog post, we will delve into the concept of nullish coalescing and explore how it can be leveraged to write cleaner, more robust code.

Understanding the Problem

In JavaScript, null and undefined are commonly used to represent the absence of a value. However, when handling these values, a common pitfall occurs. Consider the following scenario:

let defaultValue = "Default Value";
let value = null;

let result = value || defaultValue;

console.log(result); // Output: "Default Value"

In the code snippet above, the intention was to assign the value of value to result. However, since value is null, JavaScript evaluates it as “falsy” and proceeds to assign the defaultValue instead. While this behavior might seem acceptable in some cases, it can lead to unintended consequences and logical errors if the value is meant to be a valid, “falsy” value like 0 or an empty string.

Enter Nullish Coalescing

To overcome the shortcomings of the logical OR operator (||), ECMAScript 2020 introduced the nullish coalescing operator (??). The nullish coalescing operator evaluates the expression on its left-hand side and returns it if it is not nullish (null or undefined). Otherwise, it evaluates the expression on the right-hand side and returns that value.

let defaultValue = "Default Value";
let value = null;

let result = value ?? defaultValue;

console.log(result); // Output: null

In this updated example, the nullish coalescing operator ensures that result remains null since value is explicitly null. It differentiates between nullish values and valid falsy values, providing a more accurate representation of the actual data.

Use Cases and Benefits

Nullish coalescing can greatly simplify code and improve its readability in several scenarios:

  1. Default Values: When assigning default values to variables, nullish coalescing allows for concise and explicit syntax.

    let username = null;
    let defaultUsername = "Guest";
    
    let displayName = username ?? defaultUsername;
    
    console.log(displayName); // Output: "Guest"
    
    
  2. Function Arguments: Nullish coalescing is useful when passing arguments to functions, ensuring that default values are assigned only when necessary.

    function greetUser(name) {
      name = name ?? "Anonymous";
      console.log(`Hello, ${name}!`);
    }
    
    greetUser(); // Output: "Hello, Anonymous!"
    greetUser("John"); // Output: "Hello, John!"
    
    
  3. Optional Object Properties: When accessing properties in nested objects, nullish coalescing can prevent errors when a property is missing or nullish.

    const user = {
      name: "John",
      address: null
    };
    
    let city = user.address?.city ?? "Unknown";
    
    console.log(city); // Output: "Unknown"
    

Bonus Tip: Nullish Coalescing Assignment

In addition to the nullish coalescing operator (??), ECMAScript 2021 introduced the nullish coalescing assignment operator (??=). This operator combines the nullish coalescing behavior with assignment, allowing for concise and efficient code when dealing with nullish values. Let’s explore an example to understand its usage:

let existingValue = "Existing Value";
let newValue = null;

existingValue ??= newValue;

console.log(existingValue); // Output: "Existing Value"

In this example, the nullish coalescing assignment operator (??=) is used to assign the value of newValue to existingValue only if existingValue is nullish (null or undefined). Otherwise, existingValue remains unchanged.

The nullish coalescing assignment operator proves particularly useful when updating existing values or setting default values for variables without overwriting non-nullish values. It eliminates the need for additional conditional checks and provides a concise way to handle nullish scenarios.

let username = null;
let defaultUsername = "Guest";

username ??= defaultUsername;

console.log(username); // Output: "Guest"

In this example, if username is nullish, it will be assigned the value of defaultUsername using the nullish coalescing assignment operator. However, if username already holds a non-nullish value, it remains unchanged.

Conclusion

Nullish coalescing in JavaScript provides an elegant solution for handling null or undefined values, offering cleaner and more robust code. By utilizing the nullish coalescing operator (??), developers can accurately assign default values, handle function arguments, and access optional object properties. Additionally, the nullish coalescing assignment operator (??=) further optimizes value assignment efficiency. Embrace these features introduced in ECMAScript 2020 and 2021, respectively, to enhance your JavaScript codebase. Ensure your JavaScript environment supports these features to fully utilize their benefits in your projects.

Follow me on Twitter (@daryllukas) for more JavaScript lessons like this.