Optional chaining❓in JavaScript | Adding null checks

Publicado em: 03 Julho 2024
no canal de: 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.


Nesta página do site você pode assistir ao vídeo on-line Optional chaining❓in JavaScript | Adding null checks duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário Mayank Srivastava 03 Julho 2024, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 1,354 vezes e gostou 52 espectadores. Boa visualização!