Linguine Code

What is JavaScript optional chaining and how to use it

ES6 JavaScript has provided very useful tools such as spread operator, arrow functions, Map, and more.

But one feature that I’m excited to see coming to the language is called optional chaining.

What is Optional Chaining

Optional chaining allows an engineer to reference a property in an object without throwing an error!

How to use JavaScript optional chaining

Let’s take a look at this code example.


// These objects are coming from a REST API.
const person = {
  name: 'Ruben Leija',
  hobbies: {
    cats: false,
    dogs: true,
    sports: {
      soccer: true,
      baseball: false,
    }
  }
};

const person2 = {
  name: 'John Doe',
  hobbies: {
    cats: false,
    dogs: true,
  }
};

Above, we have a simple object with other nested objects, and we’re going to pretend that these objects are coming from a REST API.

Let’s see if this person 1 and person 2 like soccer.


// true
console.log(person.hobbies.sports.soccer);

// Uncaught TypeError: Cannot read property 'soccer' of undefined
console.log(person2.hobbies.sports.soccer);

Great! Person 1 does like soccer.

But, when trying to figure out if person 2 likes soccer, I got an error. These kind of errors will break your JavaScript applications.

To prevent this from happening we have to write conditionals to check that the properties exist.


if (
  person
  && person.hobbies
  && person.hobbies.sports
  && person.hobbies.sports.soccer) {
  // ...some code execution
}

if (
  person2
  && person2.hobbies
  && person2.hobbies.sports
  && person2.hobbies.sports.soccer) {
  // ...some code execution
}

That just doesn’t look very appealing to write, and makes code harder to read.

Luckily, optional chaining helps us solve this problem! Let’s take a look at how this looks.


console.log(person2?.hobbies?.sport?.soccer);

Almost the same as the example 2 code blocks above!

The only difference is that we must add the ? symbol before going to the next object property.

This works with other ways to reference a property within an object.


// Different optional chaining types

// Example 1
const name = person?.name;

// Example 2
const name = person?.['name'];

// Example 3
const key = 'name';
const name = person?.[key];

This can also work for methods or functions within an object.


// If it existed, it would execute.
// But since it doesn't exist, nothing happens.
person?.greet();

At the time of writing this, this feature is not available to any browsers. But it will be available in TypeScript version 3.7.

Conclusion

Some folks in the community have been against this feature, because they believe an engineer should know how to validate an object.

I somewhat agree with that statement, but writing nested object is tedious task. So I welcome it with open arms.

Happy coding!