Optional Chaining and Nullish Coalescing in JavaScript
Safely reading nested values and setting defaults with ?. and ??.
There are times when you need a value buried deep inside an object, but you're not sure every level exists. Before now you had to check each level along the way:
const city = user && user.address && user.address.city
Two new operators clean this up: optional chaining (?.) and nullish coalescing
(??). Chrome 80 shipped both last month, Firefox 74 ships them this week and
Safari support is on the way. Both are on track to be part of ES2020.
Optional Chaining
?. stops and returns undefined if the value on its left is null or
undefined, instead of throwing an error:
const user = { name: "Pam" }console.log(user.address.city) // TypeError: Cannot read property 'city' of undefinedconsole.log(user?.address?.city) // undefined
It works with arrays and function calls too:
const firstTag = post.tags?.[0]// only calls onSave if it was passed inprops.onSave?.()
The function call version is handy for optional callbacks, since you no longer
need if (props.onSave) props.onSave().
Nullish Coalescing
?? gives you a default value when the left side is null or undefined:
const name = user.nickname ?? "Anonymous"
You've probably used || for this, but || falls back on any falsy value,
including 0, "" and false. That's often not what you want:
const settings = { volume: 0, title: "" }settings.volume || 50 // 50, oopssettings.volume ?? 50 // 0settings.title || "Untitled" // "Untitled"settings.title ?? "Untitled" // ""
?? only falls back when the value is actually missing, so a volume of 0
stays 0.
Using Them Together
These two work really well together. Read a nested value safely, then give it a default:
const city = user?.address?.city ?? "Unknown"
Can I Use Them Today?
If you're using Babel, yes. Create React App 3.3 and TypeScript 3.7 already
support both, so if your project is up to date there's nothing to set up. For
other Babel projects, add the @babel/plugin-proposal-optional-chaining and
@babel/plugin-proposal-nullish-coalescing-operator plugins.
Note: Don't use ?. everywhere. If a value should always be there, a thrown
error is more helpful than a quiet undefined.
Have some feedback on this post? .