简体   繁体   中英

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?

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 } = {}) => {
   ...
};

You can do this { opt1, opt2, opt3 } = {} when declaring the function.

You can do:-

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

   ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM