Home ยป JavaScript Nullish Coalescing Operator : A Complete Tutorial with Examples

JavaScript Nullish Coalescing Operator : A Complete Tutorial with Examples

The nullish coalescing operator (??) in JavaScript is used to handle null or undefined values.

It provides a way to assign a default value when dealing with variables that might have null or undefined values.

This operator is particularly useful when you want to ensure that a variable has a valid value without mistakenly overriding falsy values like 0, false, or an empty string (“”).

Syntax

let result = variable1 ?? defaultValue;

variable1: The value to be checked.
defaultValue: The value that will be used if variable1 is null or undefined.

How It Works

The ?? operator returns the right-hand side (defaultValue) if the left-hand side (variable1) is null or undefined. Otherwise, it returns the left-hand side.

Examples

1. Basic Usage of Nullish Coalescing Operator

let user = null;
let defaultUser = "Guest";

let username = user ?? defaultUser;

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

Explanation

Here, user is null, so user ?? defaultUser returns “Guest”.
If user were a non-null or defined value, it would have returned that value.

2. Handling undefined Values

let age;
let defaultAge = 25;

let userAge = age ?? defaultAge;

console.log(userAge); // Output: 25

Explanation

age is undefined, so age ?? defaultAge returns 25.
The nullish coalescing operator provides the default value when the variable is undefined.

3. Difference Between ?? and || (Logical OR)

The logical OR (||) operator returns the right-hand value if the left-hand value is falsy (e.g., 0, false, null, undefined, “”). In contrast, the nullish coalescing operator (??) only considers null and undefined.

let count = 0;

let resultOr = count || 10; // Uses logical OR
let resultNullish = count ?? 10; // Uses nullish coalescing

console.log(resultOr); // Output: 10
console.log(resultNullish); // Output: 0

Explanation

count || 10 returns 10 because 0 is a falsy value.
count ?? 10 returns 0 because ?? only checks for null or undefined. Since count is 0 (not null or undefined), it is used as the result.

4. Nullish Coalescing with Strings

let userInput = "";
let defaultText = "Default Text";

let output = userInput ?? defaultText;

console.log(output); // Output: ""

Explanation

userInput is an empty string (“”), which is not null or undefined.
Therefore, userInput ?? defaultText returns userInput, which is “”.

5. Using ?? with Function Parameters

You can use the nullish coalescing operator to set default values for function parameters when they are null or undefined.

function greet(name) {
  let displayName = name ?? "Guest";
  console.log(`Hello, ${displayName}!`);
}

greet("Alice"); // Output: "Hello, Alice!"
greet(null);    // Output: "Hello, Guest!"
greet();        // Output: "Hello, Guest!"

Explanation

In the greet function, name ?? “Guest” ensures that “Guest” is used if name is null or undefined.
When called with “Alice”, displayName becomes “Alice”.
When called with null or without a parameter, displayName becomes “Guest”.

6. Chaining with Multiple ?? Operators

You can chain multiple nullish coalescing operations to find the first defined value.

let val1 = null;
let val2 = undefined;
let val3 = "Hello";

let result = val1 ?? val2 ?? val3 ?? "Default Value";

console.log(result); // Output: "Hello"

Explanation

The expression val1 ?? val2 ?? val3 ?? “Default Value” checks each variable in sequence.
It stops at the first value that is not null or undefined, which in this case is “Hello”.

7. Combining with Other Operators

You can combine the nullish coalescing operator with other operators for more complex expressions.

let user = { name: null, age: 30 };

let userName = (user.name ?? "Unknown") + " (" + (user.age ?? "Age not provided") + ")";

console.log(userName); // Output: "Unknown (30)"

Explanation

user.name ?? “Unknown” checks if user.name is null or undefined. Since user.name is null, it returns “Unknown”.
user.age ?? “Age not provided” returns 30 since user.age is defined.

8. Handling Nested Objects with ??

You can use the nullish coalescing operator to handle nested objects and provide fallback values.

let user = { profile: { name: null } };

let displayName = user.profile.name ?? "Anonymous";

console.log(displayName); // Output: "Anonymous"

Explanation

user.profile.name is null, so user.profile.name ?? “Anonymous” returns “Anonymous”.

Summary

The nullish coalescing operator (??) is a powerful tool in JavaScript for handling null or undefined values. It provides a safe way to assign default values and prevents unexpected behavior when dealing with falsy values like 0, false, and “”.

Key Points

?? checks only for null or undefined.
It is useful for setting default values without overriding valid falsy values like 0, false, or “”.
Different from logical OR (||), which considers all falsy values.

The nullish coalescing operator is especially helpful when working with potentially null or undefined values in dynamic data sources like user inputs, API responses, or nested objects. It adds more control to your default value assignments.

You may also like