JavaScript-Modern Operators (Contin.)

Klioop
Nov 3, 2020
  1. Optional Chaining

Description

The optional chaining operator provides a way to simplify accessing values through connected objects when it’s possible that a reference or function may be undefined or null.

For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as:

let nestedProp = obj.first && obj.first.second;

Reference to MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)

Suppose you get data on web that consist of deeply-nested objects. Then, you want destructuring with the object. Say a deeply-nested object you get is ‘restaurant’.

And, you want to access to restaurant.first.second sub-properties. In the real world data, some subproperties have no or undefined values. It forces you to check whether the properties have values or not to access the property interested. Even, the property itself could have null or undefined.

Without optional chaining, to access the ‘second’ property of ‘restaurant’ object you should write like following:

if (restaurant.first && restaurant.first.second) const secondProperty = restaurant.first.second

With optional chaining, the above code can be really simplified:

const secondProperty = restaurant.first?.second?

If the value of restaurant.first or restaurant.first.second is null or undefined, the secondProperty is assigned to undefined.

--

--