Retrieving Undefined Object Properties

Protect against trying to retrieve values from undefined properties

by mmansion

JavaScript

/*
JavaScript can crash because a particular implementation doesn't support a particular object whose properties and methods we are trying to access. 

To protect against this sort of error we use the && operator as follows:
*/

var myObj = {};

myObj.prop = {};

var refToObjProp = myObj && myObj.prop

if (refToObjProp) { // code to process style if supported goes here
    console.log("supported");
} else {
    console.log("not supported");
}