Remember this error from Grade 8? The most common error in 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:
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."
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:
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 ifobjexistsarr?.[index]: read an index, but only ifarrexistsobj.method?.(): call a method, but only if it exists
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.