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.

\$\endgroup\$
1
\$\begingroup\$

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

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

Array Destructuring

\$\endgroup\$
  • \$\begingroup\$ Only for undefined, not for null \$\endgroup\$ – Blindman67 Aug 3 '18 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.