If you need to do this in many consecutive functions, a way to standardize the process and speed it up is:
function setOpts (standard, user) {
if (typeof user === 'object' {
for (var key in user) {
standard[key] = user[key];
}
}
}
Then you can just define your functions simply like this:
var example = function (options) {
var opts = {
a: 1,
b: 2,
c:3
};
setOpts(opts, options);
}
This way you only define one options object inside the function, which contains the default values.
If you want to put an extra check to avoid prototype inheritance, the first function can be:
function setOpts (standard, user) {
if (typeof user === 'object') {
Object.keys(user).forEach(function (key) {
standard[key] = user[key];
});
}
}
The latter case is not supported for: IE < 9, Chrome < 5, Firefox < 4, Safari < 5
(you can check the compatibility table here)
Finally ECMAScript 6 will bring us the best way to do this: default parameters.
It will take a few months though before this is widely supported across browsers.
extend
and don't keep local variables for the options? – Editorial