Optional chaining (?.)

Optional chaining (?.)

Optional chaining is also known as Null Safety.

The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.

Syntax: obj.val?.prop

Example:

const animal = {
  name: 'Alice',
  cat: {
    name: 'Dinah',
  },
};

Output:

const dogName = animal.cat.name;
console.log(dogName);
// Expected output: Dinah

const dogName1 = animal.dog?.name;
console.log(dogName1);
// Expected output: undefined

const dogName2 = animal.dog.name;
console.log(dogName2);
// Error: Cannot read properties of undefined (reading 'name')

Description:

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

Read more