Q:

optional chaining in javascript

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
3
let myMap = new Map();
myMap.set("foo", {name: "baz", desc: "inga"});

let nameBar = myMap.get("bar")?.name;
1
/* 
* 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];
}
1
const array = [1,2,3,4,5];
let arrItem = array?.[4]; 

console.log(arrItem); /// 5
0

New to Communities?

Join the community