es2020 optional chaining code example

Example 1: conditional chaining chrome

const nameLength = db?.user?.name?.length; // property
const adminOption = db?.user?.validateAdminAndGetPrefs?.().option; // functions
const optionLength = db?.user?.preferences?.[optionName].length; // dynamic property
const userName = usersArray?.[userIndex].name; // on arrays

Example 2: optional chain operator

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

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

Example 3: optional chaining

/* 
* optional chaining (?.) allows me to write code that stops 
* running when we encounter a null or undefined value
*/

function tryGetFirstElement<T>(arr?: T[]) {
    return arr?.[0];
    // equivalent to
    //   return (arr === null || arr === undefined) ?
    //       undefined :
    //       arr[0];
}