Optional Chaining in JavaScript

?.Optional Chaining operator

Image from twitter by Daniel Rosenwasser (@Daniel Rosenwasser).

Optional chaining will eliminate the need for manually checking if a property is available in an object. With option chaining the checking will be done internally.

Example without Optional chaining.

const planet1 =  {
    name: 'Earth',
    size: '6,371 km'
  }

const planet2 = {
    name: 'Mars',
    // size: '3,389.5 km'
  }

function printPlanetInfo(planet) {
  console.log(`Name: ${planet.name}`)
  console.log(`Size: ${planet.size.toUpperCase()}`)
}

printPlanetInfo(planet1)
printPlanetInfo(planet2)

When we pass an planet object which doesn’t have the size property:

To solve the above problem what we do is, we will add check if size property available in the planet object

const planet1 =  {
    name: 'Earth',
    size: '6,371 km'
  }

const planet2 = {
    name: 'Mars',
    // size: '3,389.5 km'
  }

function printPlanetInfo(planet) {
  console.log(`Name: ${planet.name}`)
  planet.size = ( planet && planet.size &&
                  planet.size.toUpperCase())
                || "undefined"
  console.log(`Size: ${planet.size}`)
}

printPlanetInfo(planet1)
printPlanetInfo(planet2)

Using Optional Chaining

The optional chaining will check if an object left to the operator is valid (not null and undefined). If the property is valid then it executes the right side part of the operator otherwise return undefined.

function printPlanetInfo(planet) {
  console.log(`Name: ${planet.name}`)
  planet.size = ( planet?.size?.toUpperCase() ) || "undefined"
  console.log(`Size: ${planet.size}`)
}

The native JavaScript equivalent code for above optional chaining operator is

(property == undefined || property == null) ? undefined : property

Using variables as property name

We can use variables as property name in optional chaining

const planet = {
  name: 'Earth',
  size: '6,371 km'
}

planet?.size

// We can also use with expressions

planet?.["s"+"ize"] 

Functional call with optional chaining

You can use optional chaining to call a method which may not exist.

const planet = {
  name: 'Earth',
  size: '6,371 km'
  getSize() {
    return this.size;
  }
}

planet?.getSize?.()

Reference: MDN.