// Example object
const macAyres = {
tours: {
nearMe: {
sanFrancisco: {
date: 'Sun Oct 27',
location: 'The Regency Ballroom',
cost: '30.00',
},
},
}
}
// 1. Ternary Operator to Check for null/undefined
const concertLocation = (macAyres.tours &&
macAyres.tours.nearMe &&
macAyres.tours.nearMe.sanJose)
? macAyres.tours.nearMe.sanJose.location
: undefined;
// 2. Oliver Steele’s Nested Object Access Pattern
const concertLocation = (macAyres.tours.nearMe.sanJose || {}).location;
/* Explanation:
As the || operator breaks return the truthy value encountered, the above expression would return macAyres.tours.nearMe.sanJose if it is not null/undefined, otherwise {}.
In this case, we will be accessing location from an empty object, and not from undefined, so we will avoid getting the error.
*/
// 3. Array Reduce
const paths = ['tours', 'nearMe', 'sanJose', 'location'];
const location = paths.reduce((object, path) => {
return (object || {})[path]; // Oliver Steele's pattern
}, macAyres)
// 4. Try/Catch Helper Function With ES6 Arrow Function
function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}
// use it like this
getSafe(() => obj.a.lot.of.properties);
// or add an optional default value
getSafe(() => obj.a.lot.of.properties, 'nothing');
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter