Thursday, February 9, 2012

Javascript objects are not hashes

I've some across several posts from people warning about using objects as maps( [1], [2] ), and while they're right I think they miss an important feature. Objects are not hashes. Instead they try to show you how to use them like objects.

The key to the whole issue is the difference in behavior of in and hasOwnProperty.

For example if I want to set a property in an object using a user supplied string I would do this:

This makes it clear that assigning & updating a field is a ternary (append/update/fail) rather than a binary issue (append/update).

If you're feeling paranoid about already broken data, then you might change the use of posts.hasOwnProperty to,slug). But this code should prevent hasOwnProperty from getting overwritten in the first place.