What is JavaScript Double Question Mark (??) or the Nullish Coalescing Operator?

Nishil Patel

Nishil Patel

Apr 10, 2024

5 min read

Share

What is JavaScript Double Question Mark (??) or the Nullish Coalescing Operator?

In this article, we’ve covered everything about the JavaScript double question mark (??), typically known as the nullish coalescing operator in JavaScript added in ES2020. We’ve also covered the nullish assignment operator (??=) from the ES2021 JavaScript release that makes your code even more reliable and concise.

Table of Contents

1.

Introduction

2.

What is the Difference Between Nullish and Falsy Values?

3.

What is “??” Operator (Nullish Coalescing Operator) and How Does it Work?

4.

Use Cases for the JavaScript Nulling Coalescing Operator

5.

Using “??” with “||” Operator: Precedence

6.

Nullish Coalescing Assignment Operator (??=)

7.

FAQs

Introduction

The JavaScript double question mark (??) typically called the nullish coalescing operator uses the theory of “nullish” instead of “falsy” to assign values to a variable.

Simply put, the double question mark (??) operator returns the right-hand operand if the left-hand operand evaluates to a nullish value (either null or undefined).

What is the Difference Between Nullish and Falsy Values?

Nullish means null or undefined values, whereas falsy values refer to null, undefined, 0, and empty strings (“”).

The difference between nullish and falsy values is important to note when evaluating the boolean results of logical statements.

What is “??” Operator (Nullish Coalescing Operator) and How Does it Work?

The nullish coalescing operator was introduced in the JavaScript ES2020 update. It functions similarly to the “OR” operator but with a fail-safe that it only considers null and undefined as false boolean values.

Just like the “OR” (||) and “AND” (&&) logical operators in JavaScript, the “??” or the double question mark short circuits the chain of logical evaluation.

Let’s quickly compare the results of two similar code snippets that show the difference between “OR” and “??” operators:  

The first one uses the “OR” operator and the other uses the nullish coalescing operator.

Example Code

// Snippet 1: Using the OR Operator (||)
const moneyCount = 0;
const savedMoney = moneyCount || 10;
console.log(`I have ${savedMoney} rupees.`); // Outputs: I have 10 rupees.
// Snippet 2: Using the Nullish Coalescing Operator (??)
const moneyCount1 = 0;
const savedMoney1 = moneyCount1 ?? 10;
console.log(`I have ${savedMoney1} rupees.`); // Outputs: I have 0 rupees.

In the first snippet, the moneyCount variable is set to 10 rupees by default using the “OR” operator (||). This is because the “OR” operator treats 0 as a falsy value, and hence, it defaults to the next truthy value, which is 10.

However, in the second snippet, the moneyCount1 variable retains its value of 0 using the nullish coalescing operator (??). This operator does not consider 0 as a falsy value, and therefore, the final result is 0.

The value 0 is a valid scenario, especially when representing a state of having no saved money. The nullish coalescing operator (??) is more accurate in this context as it respects this logic.

Here’s how you use a nullish coalescing operator (??):

const finalResult = result1 ?? result2;

With the above code, if result1 is either null or undefined, finalResult would be assigned the value of result2. Otherwise, finalResult would retain the value of result1.

Note: The nullish coalescing operator provides a concise way to write logic similar to if/else statements or with ternary operators. However, it's not at all a replacement for if/else statements or ternary operators.

Share JavaScript Errors like A Pro in a Visual Bug Report Format

Use Cases for the JavaScript Nulling Coalescing Operator

Here are some of the use cases for the nullish coalescing operator:

Assign Default Values for Missing Function Args

Code Example 1:

const welcomeMessage = (username) => {
  return `Hey! ${username ?? "New User"}. Welcome to the store.`;
};
console.log(welcomeMessage()); // Hey! New User. Welcome to the store.

Explanation:

Here, you see a missing arg for the function welcomeMessage. The default value kicks in as “New User” and the welcome message appears with the default user name.

Handle Undefined or Null Values

Code Example 2:

let initialCount;
const count = initialCount ?? 1;
console.log(count); // 1

console.log(initialCount); // undefined

Explanation:

The initialCount variable is undefined. The default value is set to 1 in the output. Although the “OR” operator would output the same, the “??” JS operator is a better option in terms of code readability when it comes to handling null or undefined values. Also, it's less confusing to read the above code.

Also Read: React JS Suspense: Work Better with Async Data

Handle 0 (Zero) as a Variable Value

Code Example 3:

const availableHotelRooms = 0;
const rooms = availableHotelRooms ?? 20;
console.log(`There are ${rooms} rooms available in the hotel.`);
// There are 0 rooms available in the hotel.

Explanation:

0 is a valid input in the code above. With the “OR” operator, the result would be the opposite.

Handle Missing Object Properties

Code Example 4:

const ninjaDetails = {
  firstName: "Itachi",
  village: "Leaf",
  clan: "Uchiha",
  specialPower: "Mangekyo Sharingan",
};

console.log(
  `${ninjaDetails.firstName} is ${ninjaDetails.age ?? "N/A"} years old.`
); // Itachi is N/A years old.

Explanation:

You can use the “??” operator to handle missing object properties. It is super useful while handling real-world data making your code reliable, concise, and very readable. Just like the above code where the age property is missing from the object which gets effectively handled by the nullish coalescing operator.

Also Read: “Objects are not Valid as a React Child” Fixing Error

Using “??” with “||” Operator: Precedence

You should account for precedence while using the “??” operator with the “||” logical operator.

The “OR” operator precedes the “??” operator in your conditional statement. It’s a good practice to use parentheses when you combine ?? with || for accurate results. Here’s how it works:

Code Example:

let totalValue;
const initialValue = 0;
const defaultValue = 10;

const finalValue = totalValue ?? (initialValue || defaultValue);
console.log(`The final value is ${finalValue}.`); // The final value is 10.

Explanation:

Without parentheses, combining “??” and “||” shows an error in your text editor. Your code won’t run correctly and your console throws the following error:

Uncaught SyntaxError: Unexpected token '||'  

Share All Your Console Logs and Device Info with Visual Bug Reports for Faster Debugging

Nullish Coalescing Assignment Operator (??=)

The nullish coalescing assignment operator (??=) is a more recent addition to the JavaScript ES2021 update. It was included in the language along with other logical assignment operators namely the logical “OR” assignment and the logical “AND” assignment operator.

Since the nullish coalescing operator is considered a special case of using a logical “OR” operator, it’s considered a special case for a logical OR assignment operator too.

Before getting to the nullish coalescing assignment operator, let’s quickly cover the logical “OR” operator along with the logical OR assignment operator. Here’s how it works:

Using Logical “OR” (||) Operator

Example Code

const user1 = {
  name: "John",
  experienceYears: 5,
};

const user2 = {
  name: "Carrie",
  job: "Analyst",
};

user1.experienceYears = user1.experienceYears || 10;
user2.experienceYears = user2.experienceYears || 10;

console.log(user1); // {name: 'John', experienceYears: 5}
console.log(user2); // {name: 'Carrie', job: 'Analyst', experienceYears: 10}

Code Explained:

In the “OR” operator, if the first value is truthy, that first operand will immediately be returned and the second operand is not evaluated. With this concept, the experienceYears with the value 10 is assigned only to the user2 object. The object user1 already has a truthy value 5 assigned for the existing experienceYears property, and so it remains unaltered.

Using Logical “OR” Assignment (||=) Operator: Shortcut for Using Logical OR Operator

Example Code

const user1 = {
  name: "John",
  experienceYears: 5,
};

const user2 = {
  name: "Carrie",
  job: "Analyst",
};

user1.experienceYears ||= 10;
user2.experienceYears ||= 10;

console.log(user1); // {name: 'John', experienceYears: 5}
console.log(user2); // {name: 'Carrie', job: 'Analyst', experienceYears: 10}

Code Explained:

The logical “OR” assignment operator (||=) first evaluates the value of the left operand. If that value is falsy, it goes to the right operand, takes its value, and assigns it immediately to the left operand.

Here, the experienceYears property gets added to user2 using the logical “OR” assignment operator with the new logical operator “||=” and user1 is ignored being replaced since it already bears the value of 5 for the experienceYears property.

Using Nullish Coalescing Assignment “??=” Operator

The nullish coalescing assignment operator “??=” is a powerful solution when you want only the null or undefined values to be considered as falsy. Just like the “??” operator, 0 and empty strings (“”) are considered truthy. Here’s how it works:

Example Code

const user1 = {
  name: "John",
  experienceYears: 0,
};

const user2 = {
  name: "Carrie",
  job: "Analyst",
};

user1.experienceYears ??= 10;
user2.experienceYears ??= 10;

console.log(user1); // {name: 'John', experienceYears: 0}
console.log(user2); // {name: 'Carrie', job: 'Analyst', experienceYears: 10}

Code Explained:

Here, 10 is not assigned to user1 since the user1 object already has the experienceYears property with a 0 value. The experienceYears only gets added to user2.

In a nutshell, the nullish assignment operator will assign a value to the variable if that variable is currently nullish (null or undefined). 0 and empty strings are perfectly valid and evaluated to be truthy.

FAQs

Written by

Nishil Patel | CEO & Founder

Follow

Nishil is a successful serial entrepreneur. He has more than a decade of experience in the software industry. He advocates for a culture of excellence in every software product.

Subscribe to our updates

Meet the Author: Nishil Patel, CEO, and Co-founder of BetterBugs. With a passion for innovation and a mission to improve software quality.

We never spam.

Nothing here!
Show us some love 💖. Try BetterBugs today if you haven’t already. A quick feedback and a rating on our Chrome web store page would be awesome!

Share your experience with the founderhere!

Don’t wait! Start reporting now.