If you're certain the parent object exists, then:
if(obj && obj.key) {
console.log(obj.key);
}
However, this example will fail miserably if obj
doesn't exist.
if (obj && obj.key) {
console.log(obj.key);
}
... which is why you might want to check if the object is defined when checking for the property. This ensures that you won't get runtime errors if the condition is hit and the property's object hasn't been set.
if(typeof obj != "undefined" && obj.key) {
console.log('you will not see this logged')
}
You'll notice that the above example does not throw an exception.
var obj = {key: 1};
if(typeof obj != "undefined" && obj.key) {
console.log('we have obj! and val is : ' + obj.key)
}
This is a much more defensive approach but it allows for portability. If you wanted to extract your logic into a module for reuse, you may want to check if the object exists as well or risk unwanted errors from an area of the application which you might not necessarily be concerned with.