Extending Objects in Underscore

Underscore is a very nice library, it’s what Backbone JS is built on. What I’ve come to like about it is its ability to provide very helpful functions that let you more effectively work with sets of data.

Below is the code we’ve seen before, only slightly modified because we’re using Underscore’s extend function now.

This one fills in missing properties and ignores any match applied after. Our start object was able to keep the id as 123, the count at 41 and so on. The second argument, more set the name property because it didn’t exit in start and finally the properties on extra already existed, so it had no effect on the final output.

The extend and defaults functions work almost opposite from each other, but are great to have side-by-side when you need them.

Related:

About Chris Missal

Oh hey, I'm a Senior Consultant for Headspring in Austin, TX. I've been working in software professionally since 2006 and I really, really love it. I'm mostly in the Microsoft world, but enjoy building computer things of all sorts (to be vague). When I'm not slinging code, I'm probably out and about slinging discs, bowling balls, or good beer with great friends.

You’re missing an important semantic here – _.extend modifies the first object you pass it. So after you call _.extend(start, more, extra), the start object has changed. In fact, start is the object that is returned. Your example makes it look like start isn’t modified.

jQuery’s extend does a deep copy of nested objects. Underscore’s shallow copy of nested attributes can lead to some very subtle bugs. Take a look at the following article for a good discussion of the issue: