1const adventurer = {
2 name: 'Alice',
3 cat: {
4 name: 'Dinah'
5 }
6};
7
8const dogName = adventurer.dog?.name;
9console.log(dogName);
10// expected output: undefined
1let myMap = new Map();
2myMap.set("foo", {name: "baz", desc: "inga"});
3
4let nameBar = myMap.get("bar")?.name;
1/*
2* optional chaining (?.) allows me to write code that stops
3* running when we encounter a null or undefined value
4*/
5
6function tryGetFirstElement<T>(arr?: T[]) {
7 return arr?.[0];
8 // equivalent to
9 // return (arr === null || arr === undefined) ?
10 // undefined :
11 // arr[0];
12}
13
1const array = [1,2,3,4,5];
2let arrItem = array?.[4];
3
4console.log(arrItem); /// 5