Determining if an object property exists | NCZOnline:
//doesn't accurately test for existence
if (person.name){
//yay! property exists!
}

At first glance, this seems okay. However, understanding how JavaScript works reveals some problems with this approach. First, this will only succeed if the value of person.name is truthy, meaning itโ€™s an object, a non-empty string, a non-zero number thatโ€™s not NaN, true, and not null or undefined. That means if person.name is the empty string (โ€œโ€), this check will fail. Failing, in this case, doesnโ€™t mean that the property doesnโ€™t exist. In fact, the property does exist and contains a value, but the value is falsy and so doesnโ€™t pass this test. [emph mine -mfn]


In retrospect, he's only going Colbert on us twice, but it made me chuckle anyhow. I'd seen the truthy phrase before, but not used with quite so much unselfconscious aplomb.

And I wondered about that shortcut check for existence. It looks like what I want is, indeed, if ('propertyName' in object), though hasOwnProperty() comes up again as well if you want an object-specific check.

In other news, I'm over 2000 posts -- blogger says 2007. I've almost blogged my year. Sorta. Which answers the question: If over two thousand blog posts fall in the woods...

Labels: ,