Optional chaining❓in JavaScript | Adding null checks

Veröffentlicht am: 03 Juli 2024
auf dem Kanal: Mayank Srivastava
1,354
52

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.


Auf dieser Seite können Sie das Online-Video Optional chaining❓in JavaScript | Adding null checks mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Mayank Srivastava 03 Juli 2024 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 1,354 Mal angesehen und es wurde von 52 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!