In my code, I deal with an array that has some entries with many objects nested inside one another, where as some do not. It looks something like the following:
In str's answer, value 'undefined' will be returned instead of the set default value if the property is undefined. This sometimes can cause bugs. The following will make sure the defaultVal will always be returned when either the property or the object is undefined.
const temp = {};
console.log(getSafe(()=>temp.prop, '0'));
function getSafe(fn, defaultVal) {
try {
if (fn() === undefined) {
return defaultVal
} else {
return fn();
}
} catch (e) {
return defaultVal;
}
}