Posted by Arjun on Sunday 26th July 2020

JavaScript - Optional chaining (?.)

Optional chaining allows you to safely access the nested object properties. In general, to access the nested object properties you must and should check the object and it exists otherwise you may get a type error. Using the optional chaining(?.) you can avoid long nasty checks of null or undefined using && operator.

const user = {
  'name' : 'Arjun'
}

const userName = user.name;
console.log(userName);
// expected output: Arjun

const userAge = user.age;
console.log(userAge);
// expected output: undefined

const userPrject =user.project.name
console.log(userPrject);
// expected output: VM485:1 Uncaught TypeError: Cannot read property 'name' of undefined  at <anonymous>:1:32

// To avoid eror we used to do -
const userPrject = user && user.project ?? user.project.name : null;
// expected output: null

// Now you can do -
const userPrject =user.project?.name
// expected output: undefined