Hello artisan,
In this javascript best practice tutorial, I will show you how to handle missing object properties using optional chaining in javascript. Hope this tutorial will help you to write nice code.
We need to check-in nested object properties the key exists or not. So how we can do it? We can do it using optional chaining which is best practice to retrieve nested object data in JavaScript.
Let assume we have an object like below:
const user = {
firstName: 'Mahedi',
lastName: 'Hasan',
address: {
city: 'Dhaka'
}
}
Now if we fetch city from this user
object like
if(user.address.city) {
//code goes here
}
Why this above code is not perfect? If the country property does not exist, this will break the code. So if we want to safely check this country, then we can use optional chaining like that:
const countryName = user?.address?.city || 'Default Value';
Read also: Make Your If Condition More Beautiful in JavaScript
Hope it can help you.
#javascript