So I’m using an object to pass in my optional variables like so:
var foo = function (options) {
var options = options || {}; //provide a default, so that
var bar = options.bar || 42; //this doesn't fail on 'foo();'
//do stuff
};
JSLint complains that I’m overwriting options, which is what I want if it’s falsy. Actually, I should probably check if it’s an Object and elsewise throw an error to let the user know what’s up. So – on that note – what would be good form here? Anybody know a good read on this? Additionally, how would I go about writing a bunch of functions with this pattern in a DRY style?
First, you need to not reassign the
optionsargument to a var. Second, be careful with this for certain values:Inside
foo,bar == 42&baz == 'fubar'because0and""are falsy. It’s probably better to be more verbose so as to be more precise:But, to be DRY, you can create a
defaultsobject and just extend both objects to asettingsobject:Since you won’t be using
defaultsany more in this invocation it doesn’t matter that it gets mutated. Using this method: