Since undefined, 0, and "" are all "falsy" in JavaScript, this is equivalent:
if(MyObject.Prop1) {
// ...
}
Rick Waldron's "Idiomatic JavaScript" is a good reference for simplifying conditional statements without sacrificing correctness. You can test its use yourself:
function testProp(val) {
if(val) {
return val.length;
}
return "nope!";
}
var myObj = { stringProp : "foo",
emptyStrProp : "",
// undefinedProp is not defined
zeroProp : 0,
twelveProp : 12,
otherObjProp : document.createElement('div'),
arrayProp : [ 'a', 'b' ]
};
console.log( testProp( myObj.stringProp ) ); // => 3
console.log( testProp( myObj.emptyStrProp ) ); // => "nope!"
console.log( testProp( myObj.undefinedProp ) ); // => "nope!"
// of course if you're expecting values other than strings and undefined
// you'll have to account for them
console.log( testProp( myObj.zeroProp ) ); // => "nope!"
console.log( testProp( myObj.twelveProp ) ); // => undefined
console.log( testProp( myObj.otherObjProp ) ); // => undefined
console.log( testProp( myObj.arrayProp ) ); // => 2
Prop1will always be a string? Because now, if it contains the Number0, your condition will befalse. And numbers don't have a length property also.