I have a piece of code that goes like this. This piece of code works but it looks horrible.
if(typeof(d.object) != "undefined"){
if(typeof(d.object.property) != "undefined"){
if(typeof(d.object.property.length) != "undefined"){
// do the code
}
else alert("error");
}
else alert("error");
}
else alert("error");
Is there any way this can be rewritten so it does the same but more efficient. Especially because the errors are all the same.
Supposing you’re not interested in the
propertyif its length is null or0(or more generally “falsy” as suggested by Jan Dvorak), then you might make it a little more readable even without usingtry/catch:in most cases this is the way to go.
About the “falsy”, from the MDN :