JavaScript Nullish Coalescing Operator Guide with Examples

javascript nullish coalescing operator

The JavaScript nullish coalescing operator (??) gives a default value when a variable is null or undefined.

Understand the Nullish Coalescing Operator in JavaScript

The nullish coalescing operator uses two question marks ??. It checks if a value equals null or undefined.

It returns the right-hand side when the value equals null or undefined and returns the left-hand side when the value is not null or undefined.

The syntax looks like this:

let result = value ?? defaultValue;

You write it like this to avoid errors. If value equals null or undefined, then result equals defaultValue. If value has a valid value, then result equals that value.

Here is a list that shows you the reasons for this operator:

  • It avoids unwanted fallback for values like 0 or "".
  • It works only with null and undefined.
  • It provides predictable control in expressions.

Here is a quick example:

let name = null;
let finalName = name ?? "Anonymouse";
console.log(finalName);

This returns "Anonymouse". The variable name equals null, so the operator gives the right-hand side.

The Difference Between Nullish Coalescing and Logical OR

Logical OR uses || and checks if a value equals any falsy type. Falsy types include 0, false, “”, null, and undefined. Nullish coalescing uses these ?? to check only null, and undefined.

Here is a table that shows you the key differences:

OperatorConditionResult
??Checks only null and undefinedCheck for a false or true value
||Check for false or true valuereturn one of the two sides that has a true value

Here is the use case for each one:

  • Use ?? when you want default values only for null or undefined.
  • Use || when you want default values for all falsy cases.

Combine Nullish Coalescing with Optional Chaining

Optional chaining ?. stops access errors in nested objects. You can combine it with ?? to provide fallback values.

Here is an example:

let user = {};
let city = user.address?.city ?? "Unknown";
console.log(city);

This gives "Unknown" and the object has no address, so the operator gives you an extra value.

let user = { address: { city: "Paris" } };
let city = user.address?.city ?? "Unknown";
console.log(city);

This returns "Paris". The property exists, so the operator uses its actual value.

Examples of Nullish Coalescing Operator in JavaScript

Handle null values:

let score = null;
let finalScore = score ?? 50;
console.log(finalScore);

This returns 50 and the value equals null, so the operator switches to the fallback number.

The difference between zero and null:

let points = 0;
let displayPoints = points ?? 10;
console.log(displayPoints);

This gives 0. The operator does not treat zero as null or undefined.

Work with nested objects:

let profile = {};
let age = profile.details?.age ?? 18;
console.log(age);

This returns 18 and the optional chain fails to access details, so the operator provides you with a fallback.

Combine with the function return values:

function getMessage() {
  return null;
}
let message = getMessage() ?? "Default message";
console.log(message);

This prints "Default message". The function returns null, so the operator uses the string.

Wrapping Up

You learned what the nullish coalescing operator does and how to use it.
You also saw the difference between ?? and ||, and how to combine ?? with optional chaining.

Here is a quick recap:

  • ?? checks only null and undefined.
  • || checks all falsy values.
  • Combine ?. and ?? to access nested values safely.
  • Use examples to test both simple and advanced cases.

FAQs

What is JavaScript Nullish Coalescing Operator?

The ?? operator returns the right value only if the left side is null or undefined. It ignores 0, false, and "" unlike the OR operator.

let value = null ?? "default";
console.log(value); // "default"

let num = 0 ?? 10;
console.log(num); // 0

What is the difference between Nullish Coalescing and OR?

The || operator treats 0, false, and "" as false values. The ?? operator only checks null or undefined.
let a = 0 || 5;
console.log(a); // 5

let b = 0 ?? 5;
console.log(b); // 0

How do you use Nullish Coalescing with functions?

You can use ?? to set default values for function arguments.
function greet(name) {
  let user = name ?? "Guest";
  console.log("Hello " + user);
}

greet("John"); // Hello John
greet(null);   // Hello Guest

Can Nullish Coalescing Operator be combined with Optional Chaining?

Yes, you can combine ?. with ?? to avoid errors when accessing nested properties.
let user = {};
console.log(user.profile?.name ?? "Unknown"); // "Unknown"

user = { profile: { name: "Alice" } };
console.log(user.profile?.name ?? "Unknown"); // "Alice"

Similar Reads

Flatten an Array in JavaScript: Use flat() to Handle Nested Arrays

Arrays often hold other arrays. This happens with API responses, form data, or nested objects. These layers add extra steps…

Understanding JavaScript Objects with Examples

JavaScript Objects hold values as key and value pairs, and they help you store and access data. Understand the JavaScript…

JavaScript Math atan: Arc Tangent of a Number in Radians

Math.atan() function in JavaScript helps you to solve math problems in your code. It turns a number into an angle.…

JavaScript do while Loop: How it Works with Examples

The "do while" loop in JavaScript runs code once before checking the condition. Use it when the code must run…

Top 5 Code Editors: The Best IDE for JavaScript

If you are a coder, one of your primary requirements is to have a trustworthy code- editor. A Code editor…

JavaScript Logical Operators with Examples

Logical operators in JavaScript let you check conditions and combine multiple checks in your code. In this guide, you will…

JavaScript Symbol Type: How it Works with Examples

JavaScript Symbol Type gives a way to make unique values. A Symbol never matches any other value and this helps…

JavaScript switch Statement: Syntax and Examples

JavaScript switch statement checks many values without long chains. It appeared to replace stacked conditions that slow you down. Understand…

JavaScript this Keyword: How It Works in Depth with Examples

The this keyword links code, context, and object reference in JavaScript. You can use it to refer to the owner…

Print in JavaScript Console Using Log, Info, Warn, and Error

The JavaScript console is a tool in web browsers that helps you print the result to the web browser. It…

Previous Article

Mocha JavaScript Test Framework: Guide and Examples

Next Article

HTML Deprecated Tags and Modern Alternatives List

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.