Given the following path, I want to return "name" if possible or "" otherwise:
countries[0].states[0].cities[0].name
One option is to check step by step:
if(countries && countries[0]){
var states = countries[0].states;
if(states && states[0]){
var cities = states[0].cities;
if(cities && cities[0]){
var name = cities[0].name;
if(name){
return name;
}
}
}
}
return "";
Which is verbose. Another option is exception handling:
try {
var name = countries[0].states[0].cities[0].name;
return name ? name : ""; // handle null or undefined
} catch(err) {
return "";
}
But we may be uncomfortable to involve exception handling on plain logic and it also costs performance.
Is there another short/clean way to do it?