Re:Default Parameters in JavaScript
by zimbatm on Tuesday March 19, 2013 @12:19PM
(#5401785)
One problem though it that it's modifying the opts parameter so it might create unwanted side-effects.
[ Parent
| on HN ]
As with _.extend, _.defaults takes 1..n arguments and will fold 2..n into 1. If you fear callers will pass in an object they rely on for function options (doubtful, but why not) you can just write:
var actual_opts = _.defaults({}, opts, {
// Your defaults here
});
where ``opts`` is the options object passed in.This also fixes the issue of a caller passing in no options (or "null" or "undefined") without having to add an `||`