0
\$\begingroup\$

I have the following code:

let id = '';
let text = '';
// Note: `match` = [full match, id (first group), text (second group)]
if (match.length > 1) {
 [, id] = match;
}
if (match.length > 2) {
 [, id, text] = match;
}
return { id, text };

match could be null, or lengths between 1-3.

id and text need to be empty strings by default and only set if match is not null and of certain length.

How can I shorten this up?

Possibly avoiding the if statements.

asked Aug 3, 2018 at 11:52
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

I discovered that array destructing has the capability of providing default values.

const [, id = '', text = ''] = match;
return { id, text };

Array Destructuring

answered Aug 3, 2018 at 13:00
\$\endgroup\$
1
  • \$\begingroup\$ Only for undefined, not for null \$\endgroup\$ Commented Aug 3, 2018 at 14:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.