Monday, 29 July, 2019 UTC


Summary

For all of the improvements that the JavaScript language has added over the past few years, like the spread operator, default argument values, and arrow functions, there are still a few features I’d love to see implemented. One such feature is optional chaining. Optional chaining allows developers to reference object properties which may or may not exist without trigger an error.
Take the following example case:
const person = {
  name: "David",
  skills: {
    javascript: {
      frameworks: ["MooTools", "React"],
    }
  },
  save: () => { }
};

// Property that *doesn't* exist (css)
person.skills.css.frameworks;
// Uncaught TypeError: Cannot read property 'frameworks' of undefined
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:
const frameworks = person?.skills?.javascript?.frameworks;
If ever a property doesn’t exist, the chaining stops and undefined is returned. Optional chaining also supports bracket syntax:
const language = "javascript";
const frameworks = person?.skills?.[language]?.frameworks;
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:
const { frameworks, doesntExist } = person.skills?.javascript;
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.
Optional chaining seems like a somewhat controversial change. It’s been argued that developers should know and validate the objects they’re using; on the other hand, the continuous nested property checking is a nightmare. I look forward to optional chaining in JavaScript. What are your thoughts?
The post Optional Chaining appeared first on David Walsh Blog.