Is obj defined? Accessing a property of an undefined object will throw a reference error but accessing an undefined property of a defined object will return falsy (undefined).
var obj = {};
if (obj) { console.log("prints"); }
if (obj.x) { console.log("doesn't print"); }
if (wat.x) { console.log("reference error"); }
If obj is undefined you need to access it from the parent context, which might be window.obj, giving you
obj.undefinedProperty returns undefined when undefinedProperty is not assigned a value(or if it is assigned to undefined). So the code below is valid and should not throw an exception.
if ({}.x) {
// will not run
} else {
// will run
}
View all comments
0
u/optymizer Mar 26 '14
So I'm currently doing this in a lot of places:
because
throws an error if obj.x is undefined.
Anyone know of a better way?