LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

Optional Chaining and Nullish Coalescing Operators

JavaScript operators: optional chaining and nullish coalescing. They help us handle missing data without unexpected errors or unwanted default values. You will often use them when reading API responses, user profiles, product details and nested objects.

Optional Chaining and Nullish Coalescing in JavaScript

Quick Answer: Optional chaining (?.) safely reads a property, calls a method, or accesses an array item when something may be missing. Nullish coalescing (??) provides a fallback only when a value is null or undefined. Together, they help us write safer JavaScript with fewer unnecessary checks.

1. Why Do We Need These Operators?

Imagine a hospital manages 10,000 patient appointments.

Each appointment may contain patient details, contact information, and a preferred phone number.

But some patients may not have provided every detail.

How will we read those details without breaking the application?

Think about an appointment received from a hospital system.

The patient may exist, but their contact information may be missing.

We must handle that situation safely.

The problem without optional chaining

Consider three appointments from a hospital system.

The first has complete details. The second has no contact object. The third has no patient.

Example 1: Reading patient details with direct property access

This example shows why repeated null checks become necessary.

const appointments = [
  {
    patient: {
      name: "Priya",
      contact: { phone: "9876543210" }
    }
  },
  {
    patient: {
      name: "Ravi",
      contact: null
    }
  },
  {
    patient: null
  }
];

for (const appointment of appointments) {
  const phone = appointment.patient.contact.phone;
  console.log(phone);
}

Expected result

9876543210
TypeError: Cannot read properties of null

Important: The loop stops when it reaches Ravi's appointment. JavaScript cannot read contact.phone when contact is null.

What goes wrong?

  1. Missing patient details can stop the current operation.
  2. Every nested property needs another check.
  3. Long conditions make the code harder to read.
  4. New fields add more places for mistakes.

Now imagine handling thousands of appointments from different systems.

Some records may be complete. Others may contain missing fields.

We need a clear way to handle these values.

The solution with optional chaining

Optional chaining checks each link before reading the next property.

If a link is missing, the expression returns undefined.

The application can then continue without that property access throwing an error.

Example 2: Safely reading patient contact details

const appointments = [
  {
    patient: {
      name: "Priya",
      contact: { phone: "9876543210" }
    }
  },
  {
    patient: {
      name: "Ravi",
      contact: null
    }
  },
  {
    patient: null
  }
];

for (const appointment of appointments) {
  const phone = appointment.patient?.contact?.phone;
  console.log(phone);
}

Expected output

9876543210
undefined
undefined

The same records now work without repeated checks.

Without and with optional chaining

Comparing direct access and optional chaining
Without optional chaining With optional chaining
appointment.patient.contact.phone appointment.patient?.contact?.phone
Needs checks before missing values. Checks each optional link.
Can throw a TypeError. Returns undefined for a missing link.
Nested conditions can become lengthy. The property path stays easy to read.

The idea to remember

  • Null = an intentional empty value.
  • Undefined = a value that has not been assigned.
  • Optional chaining = safely continue only when the current value exists.
  • Nullish coalescing = use a fallback for null or undefined.
  • Fallback = a value used when the preferred value is missing.

2. How Optional Chaining Works

Optional chaining uses the ?. operator.

It checks whether the value before it is nullish.

Nullish means the value is either null or undefined.

If the value is nullish, JavaScript stops that optional chain.

It returns undefined instead of throwing a property-access error.

Animation 1: Follow the patient contact path

This diagram follows the appointment data from the patient to the phone number.

Patient contact lookup

A missing link safely ends the property lookup.

Appointment appointment.patient
NEXT
Patient patient?.contact
NEXT
Contact contact?.phone
Phone number or undefined

The highlighted stages show the safe property path. A missing value stops the lookup and returns undefined.

Example 3: Accessing nested properties

const appointment = {
  patient: {
    name: "Priya",
    contact: {
      phone: "9876543210"
    }
  }
};

const patientName = appointment.patient?.name;
const phone = appointment.patient?.contact?.phone;
const email = appointment.patient?.contact?.email;

console.log(patientName);
console.log(phone);
console.log(email);

Expected output

Priya
9876543210
undefined

Notice that email does not exist.

The missing property returns undefined without throwing an error.

Optional chaining with arrays

We can also use optional chaining with array indexes.

This is useful when an API may return no appointments.

Example 4: Reading the first appointment safely

const appointments = [
  { patientName: "Priya" },
  { patientName: "Ravi" }
];

const firstPatient = appointments?.[0]?.patientName;
const missingPatient = appointments?.[5]?.patientName;

console.log(firstPatient);
console.log(missingPatient);

Expected output

Priya
undefined

The ?.[0] syntax checks the array first.

The next optional chain checks the selected item.

Optional chaining with function calls

Some patient records may include an optional callback.

A callback is a function passed to another part of the application.

We can call it safely when it exists.

Example 5: Calling an optional notification function

const appointment = {
  patientName: "Priya",
  sendReminder: function () {
    console.log("Reminder sent to Priya");
  }
};

appointment.sendReminder?.();

const anotherAppointment = {
  patientName: "Ravi"
};

anotherAppointment.sendReminder?.();

Expected output

Reminder sent to Priya

The second appointment has no reminder function.

The optional call safely skips that missing function.

Remember: sendReminder?.() checks whether the function exists. It does not silently ignore a value that exists but is not callable. A non-function value can still cause a TypeError.

3. How Nullish Coalescing Works

Optional chaining may return undefined for missing information.

Sometimes we want to show a default value instead.

Nullish coalescing helps us do that.

The operator is ??.

It checks the value on its left side.

If that value is null or undefined, it uses the right side.

Otherwise, it keeps the original value.

Example 6: Providing a default phone number

const appointment = {
  patient: {
    name: "Priya",
    contact: null
  }
};

const phone =
  appointment.patient?.contact?.phone ?? "Not provided";

console.log(phone);

Expected output

Not provided

Optional chaining safely reads the phone number.

Nullish coalescing supplies a readable value when it is missing.

Animation 2: The fallback decision

This diagram shows how JavaScript chooses the original or default value.

Nullish value decision

Only null and undefined move to the fallback value.

Read value Patient phone number
CHECK
Nullish? null or undefined
CHOOSE
Fallback "Not provided"
Final value is ready to display

The animation highlights the value check and fallback path. Existing values remain unchanged, including empty strings and zero.

Nullish coalescing does not replace every falsy value

JavaScript has values that are considered falsy.

Falsy values behave like false in certain conditions.

Examples include zero, false, and an empty string.

These values may still be valid application data.

Nullish coalescing preserves them.

Example 7: Keeping valid patient settings

console.log(0 ?? 10);
console.log(false ?? true);
console.log("" ?? "Not provided");
console.log(null ?? "Not provided");
console.log(undefined ?? "Not provided");

Expected output

0
false

Not provided
Not provided

The empty third output line represents an empty string.

Zero remains zero. False remains false.

4. Nullish Coalescing vs Logical OR

Both operators can provide fallback values.

However, they do not treat values in the same way.

|| uses the fallback for every falsy value.

?? uses the fallback only for null and undefined.

Example 8: Why zero can matter

Imagine a hospital stores the number of previous visits.

A value of zero means the patient has no previous visits.

That is valid information, not missing information.

const previousVisits = 0;

const usingOr = previousVisits || 1;
const usingNullish = previousVisits ?? 1;

console.log(usingOr);
console.log(usingNullish);

Expected output

1
0

The logical OR operator replaces zero with one.

Nullish coalescing correctly keeps the zero value.

Logical OR compared with nullish coalescing
Value Value || fallback Value ?? fallback
undefined Fallback Fallback
null Fallback Fallback
0 Fallback 0
false Fallback false
"" Fallback ""
"Priya" "Priya" "Priya"

Use || when every falsy value should trigger a fallback.

Use ?? when only missing values need a fallback.

5. Combine Optional Chaining and Nullish Coalescing

These operators work especially well together.

Optional chaining safely reads nested data.

Nullish coalescing provides a useful default.

Animation 3: From appointment data to a display value

This workflow combines both operators in one practical operation.

Appointment summary workflow

Safe property access followed by a meaningful fallback.

Appointment data patient.contact.phone
SAFE READ
Optional chaining ?.contact?.phone
FALLBACK
Nullish coalescing ?? "Not provided"
Ready for the appointment screen

The first stages safely read nested data. The final stage supplies a fallback only when the result is null or undefined.

Example 9: Building a safe appointment summary

const appointment = {
  id: 501,
  patient: {
    name: "Priya",
    contact: {
      phone: "9876543210"
    }
  }
};

const patientName =
  appointment.patient?.name ?? "Unknown patient";

const phone =
  appointment.patient?.contact?.phone ?? "Not provided";

const email =
  appointment.patient?.contact?.email ?? "Not provided";

console.log("Patient:", patientName);
console.log("Phone:", phone);
console.log("Email:", email);

Expected output

Patient: Priya
Phone: 9876543210
Email: Not provided

This pattern is useful when displaying data from an API.

It keeps missing fields from breaking the display logic.

6. Optional Chaining with Dynamic Property Names

JavaScript also supports optional chaining with bracket notation.

This helps when the property name comes from a variable.

Example 10: Reading a selected contact field

const patient = {
  contact: {
    phone: "9876543210",
    email: "priya@example.com"
  }
};

const selectedField = "email";

const selectedValue =
  patient.contact?.[selectedField] ?? "Not available";

console.log(selectedValue);

Expected output

priya@example.com

The brackets let us choose a property at runtime.

The optional chain still protects against a missing contact object.

7. The Nullish Assignment Operator

JavaScript also provides the ??= operator.

It is called nullish assignment.

It assigns a value only when the current value is nullish.

This is useful when we want to fill missing settings.

Example 11: Setting a default reminder message

const appointment = {
  reminderMessage: null
};

appointment.reminderMessage ??= "Your appointment is confirmed";

console.log(appointment.reminderMessage);

appointment.reminderMessage ??= "Another reminder";

console.log(appointment.reminderMessage);

Expected output

Your appointment is confirmed
Your appointment is confirmed

The first assignment fills the missing message.

The second assignment does nothing because a value already exists.

Important: ??= does not replace an empty string, zero, or false. It assigns only when the left value is null or undefined.

8. Common Mistakes and Best Practices

Mistake 1: Using only one optional chain

Every link that may be missing needs protection.

Wrong approach

const phone = appointment.patient?.contact.phone;

If patient exists but contact is null, this can still fail.

Correct approach

const phone = appointment.patient?.contact?.phone;

Protect every uncertain link in the property path.

Mistake 2: Using logical OR for every fallback

Logical OR replaces valid falsy values like zero.

Wrong approach

const visitCount = patient.visitCount || 1;

Correct approach

const visitCount = patient.visitCount ?? 1;

Choose the operator based on what missing means in your data.

Mistake 3: Using optional chaining on an undeclared variable

Optional chaining does not protect an undeclared variable.

JavaScript still throws a ReferenceError in this situation.

Wrong approach

console.log(patientDetails?.name);

Correct approach

let patientDetails;
console.log(patientDetails?.name);

Declare the variable before using optional chaining.

Mistake 4: Using optional chaining on the left side of assignment

Optional chaining is not a valid assignment target.

Wrong approach

appointment.patient?.name = "Priya";

Correct approach

if (appointment.patient) {
  appointment.patient.name = "Priya";
}

Use a normal condition when you need to assign a nested property.

Mistake 5: Mixing nullish coalescing with logical operators without parentheses

JavaScript does not allow direct mixing of ?? with || or &&.

Add parentheses to make the intended order clear.

Wrong approach

const displayName = patientName ?? fallbackName || "Guest";

Correct approach

const displayName = patientName ?? (fallbackName || "Guest");

Best practices

  • Use optional chaining for properties that may be missing.
  • Use nullish coalescing when only null and undefined need defaults.
  • Use logical OR when all falsy values should trigger a fallback.
  • Keep API response handling clear and easy to review.
  • Do not hide unexpected data problems with meaningless defaults.
  • Use explicit validation when a field is mandatory for business rules.
  • Keep optional chains short enough for other developers to understand.

9. Performance and Real-World Considerations

These operators make common data access easier to read.

They do not replace proper data validation.

They also do not guarantee that API responses are correct.

When optional chaining helps

  • Reading nested API responses.
  • Working with optional user profile fields.
  • Calling optional callbacks or event handlers.
  • Accessing optional array items.
  • Reading configuration values that may not exist.

When explicit checks are better

  • A patient identifier must exist before saving an appointment.
  • A payment amount must pass business validation.
  • A required phone number must follow the expected format.
  • A missing field must produce a clear validation message.

Production rule: Do not use optional chaining to silently accept missing required data. Use it for genuinely optional fields. Validate mandatory fields before processing or saving them.

10. How This Comes Up in Interviews

Question 1: What is optional chaining in JavaScript?

What the interviewer wants: They want to know how you handle missing nested values.

Strong answer: Optional chaining uses the ?. operator. It safely reads a property when the current value may be null or undefined. If that value is missing, the expression returns undefined. I use it when reading optional fields from API responses.

Question 2: What is nullish coalescing?

What the interviewer wants: They want to check your understanding of fallback values.

Strong answer: Nullish coalescing uses the ?? operator. It returns the right-side value only when the left side is null or undefined. It preserves valid values like zero, false, and an empty string.

Question 3: What is the difference between ?? and ||?

Strong answer: Logical OR checks for any falsy value. Nullish coalescing checks only null and undefined. For example, zero is replaced by OR, but it remains zero with nullish coalescing. I choose the operator based on the business meaning of the value.

Question 4: Can optional chaining prevent every runtime error?

Strong answer: No. It protects a property access or call when its current value is nullish. It does not protect undeclared variables or invalid function calls. It also does not validate the data returned by an API.

Question 5: Can we assign a value using optional chaining?

Strong answer: No. Optional chaining cannot be used as the left side of an assignment. I use a normal condition before assigning a nested property.

What interviewers expect at different levels

Interview expectations by experience level
Level Expected understanding
Junior Explain ?. and ?? with simple examples.
Senior Handle nested API data and preserve valid falsy values.
Architect Separate optional fields from required business data and validation.

11. Hands-On Practice

Beginner: Read a patient email safely

Create a patient object with a name and contact information.

Read the email using optional chaining.

Show "Email not provided" when the email is missing.

Hint: Combine ?. and ??.

Intermediate: Read the latest appointment

Create an array containing three hospital appointments.

Read the third appointment's patient name safely.

Return "No appointment found" when the item is missing.

Hint: Use appointments?.[2]?.patient?.name.

Advanced: Build a safe appointment summary

Create five appointments with different missing fields.

Some records should have no patient contact details.

Some records should contain an empty phone number.

Some records should contain a zero visit count.

Build a summary without losing valid values.

Expected result: Missing values get clear defaults. Zero and empty strings remain unchanged.

12. Frequently Asked Questions

Does optional chaining return null or undefined?

It returns undefined when an optional link is nullish.

Can I use optional chaining with arrays?

Yes. Use ?.[index] to access an array item safely.

Can I use optional chaining with functions?

Yes. Use functionName?.() for an optional function call.

Does ?? treat an empty string as missing?

No. An empty string is preserved by nullish coalescing.

Does ?? treat zero as missing?

No. Zero is a valid value and remains unchanged.

Can I combine ?? and ||?

Yes, but use parentheses to make the intended evaluation order clear.

Does optional chaining replace validation?

No. It handles missing links during access. Business validation remains necessary.

13. Next Steps and Community

You have learned how to handle missing JavaScript values safely.

You can now read nested data without writing repeated null checks.

You also know how to choose the correct fallback operator.

Try It Yourself: Build a patient appointment summary using these operators. Test it with complete and incomplete records.

Explore Further: Read the official JavaScript documentation for Optional chaining and Nullish coalescing.

Share Your Knowledge: Share your examples and explain how you handle missing API data. Discuss different approaches with other developers.

Keep your JavaScript safe, clear, and easy to maintain.

Comments & Ratings (1)

Log in or create a student account to comment and rate this article.

R

Ramandeep

★★★★★ 11 Nov 2026

Harshitha KH - Nice article! The examples are relevant and make both operators easy to understand. One suggestion would be to include a real API response example showing how these operators are used in day-to-day development. A small comparison with traditional if-condition checks would also help beginners understand their actual benefit. Keep up the good work!

H
Harshitha K H Reply
11 Nov 2026

Hello! Greetings from the UPGRADIX team.

Thank you for your valuable feedback and suggestions. We will definitely consider including these improvements in our future articles. Due to current time constraints, we have kept this article simple and focused on the core concepts. We truly appreciate your understanding and support! 😊