Back to JavaScript
2026-03-035 min read

Nullish coalescing operator (??)

Learn Nullish coalescing operator (??) step by step with clear examples and exercises.

Title: Mastering JavaScript's Nullish Coalescing Operator (??)

Why This Matters

In this lesson, we will delve deep into the fascinating world of JavaScript's nullish coalescing operator (??). This powerful tool is a big help for developers as it provides a more efficient and concise way to handle null or undefined values in your code. By understanding its usage, you will be better equipped to write cleaner, more robust code that saves time and reduces the risk of runtime errors.

Prerequisites

Before diving into the nullish coalescing operator, it's essential to have a solid grasp of the following concepts:

  1. Basic JavaScript syntax and data types (numbers, strings, arrays, objects)
  2. Variables and assignments
  3. Conditional statements (if-else)
  4. Functions
  5. Understanding the difference between null, undefined, falsy values, and truthy values
  6. Basic operator precedence in JavaScript

Core Concept

The nullish coalescing operator (??) is a logical operator that returns the right-hand side operand when its left-hand side operand is either null or undefined, and otherwise it will return the left-hand side operand. It's a shorthand version of using the logical OR (||) operator, but with the added benefit of only considering null and undefined as falsy values.

Here's an example to illustrate its usage:

let foo = null;
const defaultString = 'default string';
console.log(foo ?? defaultString); // Output: "default string"

let bar = 0;
const defaultNumber = 42;
console.log(bar ?? defaultNumber); // Output: 0

In the example above, we have two variables foo and bar. The variable foo is initially set to null, while bar has a value of 0. We then use the nullish coalescing operator (??) to provide default values for these variables. In the case of foo, since it's null, the right-hand side operand defaultString is returned, resulting in "default string" being logged to the console. For bar, since it has a value other than null or undefined, the left-hand side operand bar itself is returned, and 0 is logged to the console.

Common Uses of Nullish Coalescing Operator

  1. Assigning default values for variables that may be null or undefined.
  2. Simplifying conditional logic by avoiding unnecessary if-else statements.
  3. Improving readability and maintaining code consistency throughout your project.

Worked Example

Let's consider a scenario where we have a user object that can be either empty or contain data. We want to create a function that returns the user's email address if it exists, otherwise, it should return a default email address.

const user = { name: 'John Doe', email: null };
const defaultEmail = 'default@example.com';

function getUserEmail(user) {
// Using the nullish coalescing operator to check if email exists
return user.email ?? defaultEmail;
}

console.log(getUserEmail(user)); // Output: "default@example.com"

In this example, we create a user object with an empty email field. We then define a function called getUserEmail(), which takes the user object as an argument and returns the email address using the nullish coalescing operator (??). Since the email is null, the default email is returned, resulting in "default@example.com" being logged to the console.

Common Mistakes

  1. Forgetting the double question marks: The nullish coalescing operator requires two question marks (??) to function correctly. Using a single question mark will result in a syntax error.
// Incorrect usage
let foo = null;
const defaultString = 'default string';
console.log(foo ? defaultString); // SyntaxError: Unexpected token '?'
  1. Confusing the nullish coalescing operator with the logical OR operator: While both operators are used to provide default values, they behave differently when dealing with falsy values other than null and undefined. Be sure to use the correct operator based on your requirements.
// Incorrect usage of the logical OR operator
let foo = 0;
const defaultString = 'default string';
console.log(foo || defaultString); // Output: "0" (since 0 is considered a falsy value)
  1. Misunderstanding its precedence: The nullish coalescing operator has lower precedence than the logical OR operator (||) and higher precedence than most arithmetic operators. This means that you should use parentheses when combining multiple conditions to ensure correct evaluation order.
// Correct usage with parentheses for proper evaluation order
let foo = null;
const defaultString = 'default string';
const anotherDefaultString = 'another default string';
console.log((foo || true) ?? anotherDefaultString); // Output: "default string"

Practice Questions

  1. Given the following variables, use the nullish coalescing operator to assign a default value of 'fallback' for any variable that is either null or undefined.
let foo = null;
let bar = undefined;
let baz = 'example';
  1. Write a function called getDefaultEmail() that takes an email address as a parameter and returns the default email address if the provided email is either null, undefined, or an empty string.
  1. Create a JavaScript program that uses the nullish coalescing operator to check if a user's age is greater than 18, and if not, assigns a default age of 18 for voting purposes.
  1. (Bonus) Write a function called getUserDetails() that takes an object representing a user with optional properties for name, email, and age. The function should return an object containing the user's details, filling in missing values with their respective default values (name: 'Anonymous', email: 'anonymous@example.com', age: 18).

FAQ

What happens when both sides of the nullish coalescing operator are null or undefined?

When both sides of the nullish coalescing operator (??) are either null or undefined, it will return null. This behavior is different from the logical OR operator, which would return a truthy value in such cases.

Can I use the nullish coalescing operator with numbers?

Yes! The nullish coalescing operator can be used with both numbers and other data types. It will work as expected, returning the right-hand side operand if the left-hand side is either null or undefined, and otherwise it will return the left-hand side operand.

Is there a performance difference between using the nullish coalescing operator and the logical OR operator?

In most modern JavaScript engines, the performance difference between the nullish coalescing operator (??) and the logical OR operator (||) is negligible. However, the nullish coalescing operator provides more concise and readable code when dealing specifically with null or undefined values.

What about using the nullish coalescing operator with objects?

Yes! The nullish coalescing operator can also be used with objects. If the left-hand side operand is either null or undefined, it will return the right-hand side operand (another object). However, if both operands are objects and neither is null or undefined, it will compare them for strict equality (===), and only if they are strictly equal will it return the left-hand side operand.

Why should I prefer the nullish coalescing operator over other methods for handling null or undefined values?

The nullish coalescing operator provides several advantages:

  1. It's more concise than using conditional (if-else) statements, which can lead to cleaner and easier-to-read code.
  2. It's more efficient than using the logical OR operator (||) for handling null or undefined values specifically.
  3. It follows a consistent pattern with other comparison operators like equality (===) and inequality (!==).
Nullish coalescing operator (??) | JavaScript | XQA Learn