You've defaulted options
, but you haven't defaulted the various properties within options. Since you're supplying an object for options
, that object is being used.
You could use destructuring to supply defaults for the properties, and then supply a blank default for the parameter:
const func = (a, b, { opt1 = false, opt2 = false, opt3 = false } = {}) => {
// do something
console.log(opt1, opt2, opt3);
};
func(1, 2, {opt1: true});
func(1, 2);
Of course, you end up with the options as discrete variables rather than as an object. You can always reconstitute the object:
const func = (a, b, { opt1 = false, opt2 = false, opt3 = false } = {}) => {
const options = {opt1, opt2, opt3};
// do something
console.log(options);
};
func(1, 2, {opt1: true});
func(1, 2);
And of course, since that's your own object, you can happily assign other properties to it if you like without worrying about modifying the caller's object.
If you don't want to use destructuring, you just supply the defaults separately like we used to before ES2015, but perhaps with property spread rather than Object.assign
:
const func = (a, b, options = {}) => {
// do something
options = {opt1: false, opt2: false, opt3: false, ...options };
console.log(options);
};
func(1, 2, {opt1: true});
func(1, 2);
{ opt3: true }
as the third parameter(func(a, b, { opt3: true })
).