Take the following example case:
Attempting to get a property of an undefined parent results in a
TypeError which can brick your application. In this case we’d want to check to ensure that
css property exists:
if( person.skills && person.skills.css && person.skills.css.frameworks) // ...
I wrote a get and set utility called Objectifier to make referencing nested object properties easier, but with the Optional Chaining proposal, we now have a native way.
A simple example of optional chaining is:
const skills = person?.skills;
You can continue the pattern down the line of nested objects:
If ever a property doesn’t exist, the chaining stops and
undefined is returned. Optional chaining also supports bracket syntax:
You can also call a function without penalty:
// Calls save if exists, otherwise nothing const frameworks = person?.save();
You can even use the chaining syntax on the top level object:
addEventListener?.("click", e => ); methodDoesntExist?.(); // undefined
You can even use destructuring with optional chaining:
At the time of writing, optional chaining doesn’t appear in any browsers yet, but you can play around with optional chaining at the Babel online compiler.
The post Optional Chaining appeared first on David Walsh Blog.