Mapagam
  • JavaScript 
  • Web APIs 
  • TypeScript 
  • React 

What Is the Nullish Coalescing Operator (??) in JavaScript?

Posted on April 15, 2025 • 6 min read • 1,148 words
Share via
Mapagam
Link copied to clipboard

Learn how JavaScript's Nullish Coalescing Operator (??) simplifies default values handling for null or undefined, avoiding common pitfalls.

On this page
1. Introduction to the Nullish Coalescing Operator 1.1. Why Was the Nullish Coalescing Operator Introduced? 2. How Does the Nullish Coalescing Operator (??) Work? 2.1. Difference Between ?? and || 2.2. When to Use the Nullish Coalescing Operator 2.3. Handling Nested Nullish Values 3. Practical Use Cases of the Nullish Coalescing Operator 3.1. Setting Default Values in Functions 3.2. Working with APIs and Optional Fields 3.3. Combining ?? with Other Logical Operators 4. Caveats and Things to Keep in Mind 4.1. Conflicts with && and || 4.2. The Need for Proper JavaScript Version Support 4.3. Avoid Overusing It 5. Conclusion

JavaScript has evolved significantly over the years, introducing numerous features and operators that simplify developers’ tasks. Among these is the Nullish Coalescing Operator (??), which was added in ECMAScript 2020. This operator provides a concise way to handle null or undefined values, which often cause issues in JavaScript code.

1. Introduction to the Nullish Coalescing Operator

The Nullish Coalescing Operator (??) is a logical operator that allows developers to handle default values more easily. It returns the right-hand operand if the left-hand operand is either null or undefined. Unlike the logical OR operator (||), which can return a default value when the left operand is falsy (i.e., false, 0, NaN, "", null, undefined), the Nullish Coalescing Operator focuses solely on null and undefined.

1.1. Why Was the Nullish Coalescing Operator Introduced?

The need for the Nullish Coalescing Operator arose from a common issue developers face when using the logical OR operator (||) for setting default values. The || operator returns the right-hand value for a broader range of falsy values, which can sometimes lead to unintended behavior.

For instance:

let userAge = 0;
let age = userAge || 18; // age will be 18, but this is incorrect because 0 is a valid age

In the above example, we intended to assign a default value of 18 if userAge is null or undefined. However, since 0 is falsy, the expression incorrectly evaluates to 18. The introduction of ?? solves this issue.

2. How Does the Nullish Coalescing Operator (??) Work?

The Nullish Coalescing Operator (??) works by checking if the left operand is null or undefined. If it is, the operator returns the right operand; otherwise, it returns the left operand.

Here’s a basic example to illustrate this:

let userName = null;
let defaultName = "Guest";
let displayName = userName ?? defaultName;
console.log(displayName); // Output: "Guest"

In this example:

  • The value of userName is null, so the operator returns the right-hand value (defaultName), which is "Guest".

However, if the value of userName was any other falsy value (e.g., 0, "", or false), the operator would return the left-hand value.

let userName = "";
let displayName = userName ?? defaultName;
console.log(displayName); // Output: ""

In this case, since "" (an empty string) is not null or undefined, the operator returns the left operand (userName).

2.1. Difference Between ?? and ||

The key difference between the Nullish Coalescing Operator (??) and the logical OR operator (||) is how they treat falsy values.

  • || returns the right operand when the left operand is any falsy value (false, 0, NaN, "", null, undefined).
  • ?? returns the right operand only when the left operand is null or undefined.

Let’s look at an example to clarify the difference:

let value1 = 0;
let value2 = 0;

let resultOr = value1 || 42; // Result: 42 (because 0 is falsy)
let resultNullish = value2 ?? 42; // Result: 0 (because 0 is neither null nor undefined)

console.log(resultOr);       // 42
console.log(resultNullish);  // 0

2.2. When to Use the Nullish Coalescing Operator

The Nullish Coalescing Operator is ideal for situations where you want to provide default values only when a variable is null or undefined, but not when it has other falsy values such as 0 or "".

For example, you might want to provide a default value for a user’s age only when it is not provided (i.e., null or undefined), but you don’t want to override valid values like 0 (representing a valid age).

let userAge = 0;
let defaultAge = 30;
let age = userAge ?? defaultAge;
console.log(age); // Output: 0

2.3. Handling Nested Nullish Values

You can also use the Nullish Coalescing Operator with nested values. This is especially useful when dealing with complex objects where some properties may be missing or undefined.

let user = {
  name: "John",
  profile: {
    age: null
  }
};

let userAge = user.profile.age ?? 25;
console.log(userAge); // Output: 25 (since user.profile.age is null)

3. Practical Use Cases of the Nullish Coalescing Operator

The Nullish Coalescing Operator can be used in various scenarios. Below, we’ll explore some common use cases where this operator proves especially useful.

3.1. Setting Default Values in Functions

Functions often require default values for optional parameters. Using ?? ensures that only null or undefined values are replaced with defaults, avoiding unintended replacements when the parameter is falsy but valid.

function greet(name = "Guest") {
  console.log("Hello, " + (name ?? "Guest"));
}

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

3.2. Working with APIs and Optional Fields

When consuming APIs, it’s common to deal with optional fields that might not always be present. The Nullish Coalescing Operator helps ensure that you get sensible fallback values when these fields are null or undefined.

let apiResponse = {
  user: {
    name: "Alice",
    age: undefined
  }
};

let userAge = apiResponse.user.age ?? "Not specified";
console.log(userAge); // Output: "Not specified"

3.3. Combining ?? with Other Logical Operators

You can combine the Nullish Coalescing Operator with other logical operators such as && or || to build more complex expressions.

let userSettings = {
  theme: null,
  language: "en"
};

let theme = userSettings.theme ?? "light";
let language = userSettings.language ?? "en";

console.log(theme);    // Output: "light"
console.log(language); // Output: "en"

4. Caveats and Things to Keep in Mind

While the Nullish Coalescing Operator is incredibly useful, there are some nuances and potential pitfalls to be aware of:

4.1. Conflicts with && and ||

You cannot use the Nullish Coalescing Operator (??) in combination with the logical AND (&&) or OR (||) operators without careful parentheses, as the precedence of ?? is lower than both && and ||.

let a = null;
let b = 5;
let result = a ?? b || 10;  // Result: 10, because `??` has lower precedence than `||`
console.log(result);

In the above example, a ?? b || 10 is evaluated as (a ?? b) || 10 because ?? has lower precedence than ||. If you want a different behavior, use parentheses to group the operations properly.

4.2. The Need for Proper JavaScript Version Support

The Nullish Coalescing Operator was introduced in ECMAScript 2020. So, if you’re working in an environment that does not support this version of JavaScript (e.g., older browsers or older Node.js versions), you’ll need to use a transpiler like Babel to convert your code.

4.3. Avoid Overusing It

While the Nullish Coalescing Operator can simplify certain cases, overuse of it or using it in unnecessary situations could make your code less readable. Use it judiciously and ensure that its intent is clear in the context of your code.

5. Conclusion

The Nullish Coalescing Operator (??) in JavaScript is a valuable addition that helps developers manage default values more effectively, especially when dealing with null and undefined. It allows you to handle missing data more precisely, preventing bugs that arise from unintentionally replacing valid falsy values like 0 or "".

JavaScript   Nullish Coalescing Operator   Default Values   Programming Tips   ECMAScript 2020  
JavaScript   Nullish Coalescing Operator   Default Values   Programming Tips   ECMAScript 2020  
 JavaScript Functions Made Easy: Syntax, Parameters & Return Values
Short-Circuiting in JavaScript: Master Logical Operators Like a Pro 

More Reading!

  1. How TypeScript’s Type Inference Works (And Why It’s a Game-Changer)
  2. Short-Circuiting in JavaScript: Master Logical Operators Like a Pro
  3. TypeScript vs JavaScript Objects: Key Differences
  4. Understanding JavaScript Type Coercion: == vs === Demystified
  5. How to Detect User's Browser with the Navigator API
On this page:
1. Introduction to the Nullish Coalescing Operator 1.1. Why Was the Nullish Coalescing Operator Introduced? 2. How Does the Nullish Coalescing Operator (??) Work? 2.1. Difference Between ?? and || 2.2. When to Use the Nullish Coalescing Operator 2.3. Handling Nested Nullish Values 3. Practical Use Cases of the Nullish Coalescing Operator 3.1. Setting Default Values in Functions 3.2. Working with APIs and Optional Fields 3.3. Combining ?? with Other Logical Operators 4. Caveats and Things to Keep in Mind 4.1. Conflicts with && and || 4.2. The Need for Proper JavaScript Version Support 4.3. Avoid Overusing It 5. Conclusion
Follow me

I work on everything coding and technology

   
Mapagam
Mapagam is your go-to resource for all things related to frontend development. From the latest frameworks and libraries to tips, tutorials, and best practices, we dive deep into the ever-evolving world of web technologies.
Licensed under Creative Commons (CC BY-NC-SA 4.0).
 
Frontend
JavaScript 
Web Api 
TypeScript 
React 
Social
Linkedin 
Github 
Mapagam
Code copied to clipboard