All Articles

Optional Chaining Operator in ES2020

The optional chaining operator is my favourite becuase it reduces the amount of code written dramatically when dealing with heavily chained javascript objects. Also, this can be tremendously helpful when the content structure is not completely known.

Consider the following example:

const userInfos = {
  name: 'Bob',
  email: '',
  familyMembers: {
    brother: {
      name: 'Bobby',
      age: 16
    mother: {
      name: 'Constance',
      age: 55
    father: {
      name: 'John',
      age: 60

//To output mother's age
    && userInfos.familyMembers.mother
    && userInfos.familyMembers.mother.age

As you would already know, retirving mother’s age was a pain and the nesting level in the object was not even that deep. To solve this problem, optional chaining operator is now natively available in ES2020.

Using the optional chaining operator, we can reduce the above code to:

console.log(userInfos.familyMembers?.mother?.age); // => 55

In case the value called after ? is not found the program won’t crash and will return undefined instead.

console.log(userInfos.familyMembers?.sister?.age); // => undefined