Search code examples
javascriptecmascript-6destructuring

Destructing optional function parameters


Scratching my head trying to get this optimal. Say I have a function that takes an object as a parameter and destruct it like so:

myfunc = (options = {a:true, b:true, c:true}) => {...}

By default a b and c are true. But say I call myfunc and want b to be false:

myfunc({b:false})

well now options.b === false, but the values for a and c are gone. Is there away I can accomplish this without having to pass in a copy of the default values?

I tried something weird like

myfunc = (options = Object.assign({a:true, b:true, c:true}, options)) =>{}

but that's certainly not right.


Solution

  • You could use a default object with a destructuring for the wanted properties with the default value without using option. Then create a new one by using short hand properties.

    For other objects, you could use, with newer or babeljs, rest properties for objects.

    var myfunc = ({ a = true, b = true, c = true, ...rest } = {}) => {
            const option = { a, b, c, ...rest };
            console.log(option);
        };
    
    myfunc();             // take {} as default and the default values inside of the object
    myfunc({ b: false }); // take b and default values
    myfunc({ foo: 42 });  // take foo and all default values
    .as-console-wrapper { max-height: 100% !important; top: 0; }