Checking if variable is defined before accessing its properties I didn't write this but I noticed it in our codebase at work.

var data = object &amp;&amp; object.attribute &amp;&amp; object.attribute.data ? object.attribute.data : {};


I get that the programmer is trying to check that the variable object.attribute.datais defined before using it, but is seems like so much repeated code. What's the best way to assign data the value of object.attribute.data if it's defined, otherwise giving it a value of {}?
Are you looking for this?

var data = object &amp;&amp; object.attribute &amp;&amp; object.attribute.data || {};


Alternatively, you could create a simple function to safely index objects that may not be defined, such as:

function resolve(value) {
    return function(key) {
        return key ? resolve((value || {})[key]) : value;
    };
}


You'd use it like this:

var data = resolve(object)('attribute')('data')() || {};


If anything in the chain does not exist, it will return undefined. This might be useful if you have deeply nested and unpredictable objects, such as an object resulting from parsing JSON data from a remote resource.

http://jsfiddle.net/VHcdq/1/