Advertisement
728x90
According to MDN official docs, the optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.
The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.
js
1const adventurer = {
2
3name: "Alice",
4
5cat: {
6 name: "Dinah",
7},
8};
9
10const dogName = adventurer.dog?.name;
11
12console.log(dogName);
13// expected output: undefined
14
15console.log(adventurer.someNonExistentMethod?.());
16// expected output: undefinedAdvertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 10
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
439of476