optional chaining es2020 code example

Example 1: 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];
}

Example 2: optional chaining in javascript

let myMap = new Map();
myMap.set("foo", {name: "baz", desc: "inga"});

let nameBar = myMap.get("bar")?.name;