Search code examples
javascriptdestructuring

JavaScript optional destructuring argument in function


I have this function signature

const foo = (arg, { opt1, opt2, opt3 }) => {
   ...
};

but I'd like to have this second argument optional, such as calling the function like

foo("Hello");

However, I get

TypeError: Cannot destructure property opt1 of 'undefined' or 'null'.

So, I'm tempted to fix this with changing the function such as :

const foo = (arg, options = {}) => {
   const { opt1, opt2, opt3 } = options;

   ...
};

But was wondering if there was a more inline alternative?


Solution

  • You could assign a default object and take a destructuring at the same time.

    The result is undefined for all three destructured properties, if no second parameter or undefined.

    const foo = (arg, { opt1, opt2, opt3 } = {}) => {
       ...
    };