Monday, 26 August 2013

Side-effect free version of Underscore.js default function?

Side-effect free version of Underscore.js default function?

To initialize an object using default values I am using Underscore's
default function. According to the documentation, it works like this:
var foo = _.defaults(object, *defaults)
It is described as:
Fill in undefined properties in object with values from the defaults
objects, and return the object. As soon as the property is filled, further
defaults will have no effect.
Although it basically works fine, there is one thing I always stumble
upon: The side effect of manipulating the original object.
If I run
var foo = { bar: 'baz' };
and then say
var bar = _.defaults(foo, { dummy: 23 });
not only, bar has a property called dummy, the original foo object has
been changed as well. My current workaround is:
var bar = _.defaults({}, foo, { dummy: 23 });
Unfortunately, you can easily forget this. I think it's quite a strange
behavior that the defaults function changes an input parameter as well as
returning the result as return value. It should be either or.
How do you deal with that situation? Are there better ways to deal with this?

No comments:

Post a Comment