DEV Community

Arhan Khan
Arhan Khan

Posted on

Optional Chaining and Nullish Coalescing in JavaScript

Real data is messy. An API response is missing a field, a user object has no address, a settings object was never filled in. The old way to handle that was a ladder of && checks — ugly, repetitive, and easy to get wrong. Two modern operators fix this cleanly: optional chaining (?.) and nullish coalescing (??).

Optional chaining stops the moment it meets null or undefined and returns undefined instead of throwing an error. No more crashes from reading a property of something that does not exist.

const user = { name: "Arhan" };

// Old way
const city = user && user.address && user.address.city;

// New way
const city = user?.address?.city; // undefined, no crash
Enter fullscreen mode Exit fullscreen mode

It works for method calls and array access too. If the thing before ?. is missing, the whole expression short-circuits safely.

const result = user.getName?.(); // only calls it if the method exists
const first = users?.[0];        // undefined if users is null
Enter fullscreen mode Exit fullscreen mode

Nullish coalescing pairs perfectly with it. ?? gives you a fallback value, but only when the left side is null or undefined — unlike ||, which also treats 0, "", and false as missing. That distinction matters whenever a real value could be zero or an empty string.

const count = settings.count ?? 10;   // 0 stays 0
const countOld = settings.count || 10; // 0 becomes 10 — wrong!

const name = user?.name ?? "Guest";
Enter fullscreen mode Exit fullscreen mode

Together, these two operators turn defensive code into readable code. user?.address?.city ?? "Unknown" says exactly what it means: get the city if it exists, otherwise say Unknown. Learn them, and you will delete a surprising number of nested if checks from your codebase.

Top comments (0)