filmov
tv
Optional chaining❓in JavaScript | Adding null checks #javascript #javascriptinterview #coding
Показать описание
today I am going show you a powerful feature in JavaScript called optional chaining which makes your code cleaner when dealing with nested properties. so lets dive right in. Lets say you have an object by the name of user which has a deeply nested city property and a function getCity which can a user object like and return the city value. So inside the function we just need to fetch the city value by chaining all the keys leading to the city key in the user object and return it. Lets test out our function by passing in the user object and it works. But what if I pass an object with a missing address key. Now the function throws an error. To avoid such conditions you can add a few null checks by using the AND operator like this but this method can become messy real quickly as you might have to write a lot of checks. with Optional Chaining, you can do this in a much cleaner way, where you just need to add question marks before chaining the next key and If any part of the chain is null or undefined, the value of city will simply be undefined instead of the statement throwing an error.