Optional Chaining: ?.

Grade 13, page 5 of 12. A one-minute read.

Remember this error from Grade 8? The most common error in JavaScript?

JavaScript
const user = { name: "Lucas" };
console.log(user.address.city);

It stops with an error

Uncaught TypeError: Cannot read properties of undefined (reading 'city')

user.address is undefined, and you can't read a property of undefined. The old-fashioned fix was to check every step:

JavaScript
const city = user && user.address && user.address.city;

Ugh. Modern JavaScript has a much better way: optional chaining, written as ?.. It means: "if the thing on the left is null or undefined, stop right here and give back undefined, instead of crashing."

JavaScript
const user = { name: "Lucas" };
const fullUser = { name: "Mia", address: { city: "Lima" } };

console.log(user.address?.city);
console.log(fullUser.address?.city);

It prints

undefined
Lima

No crash! It works with arrays and method calls too:

JavaScript
const data = { tags: [] };

console.log(data.tags?.[0]);
console.log(data.comments?.[0]);
console.log(data.getSummary?.());

It prints

undefined
undefined
undefined
  • obj?.prop: read a property, but only if obj exists
  • arr?.[index]: read an index, but only if arr exists
  • obj.method?.(): call a method, but only if it exists
Watch outDon't use ?. everywhere

Optional chaining is wonderful for data that might genuinely be missing, like optional fields that come from a form or the internet. But don't sprinkle ?. on everything "just in case." If something should always exist and doesn't, you want the error, so you can find and fix the real problem. Remember from Summer School: loud bugs are better than quiet ones.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning