4

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?

3 Answers 3

13

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 } = {}) => {
   ...
};
Sign up to request clarification or add additional context in comments.

Comments

6

You can do:-

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

   ...
};

Comments

6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.