Optional chaining❓in JavaScript | Adding null checks

Published: 03 July 2024
on channel: 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.


On this page of the site you can watch the video online Optional chaining❓in JavaScript | Adding null checks with a duration of hours minute second in good quality, which was uploaded by the user Mayank Srivastava 03 July 2024, share the link with friends and acquaintances, this video has already been watched 1,354 times on youtube and it was liked by 52 viewers. Enjoy your viewing!