Yanick Rochon
Yanick Rochon

Reputation: 53531

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?

Upvotes: 4

Views: 763

Answers (3)

Saurabh Singh
Saurabh Singh

Reputation: 132

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

Upvotes: 6

Yash Goyal
Yash Goyal

Reputation: 174

You can do:-

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

   ...
};

Upvotes: 6

Nina Scholz
Nina Scholz

Reputation: 386550

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

Upvotes: 13

Related Questions