\$\begingroup\$
\$\endgroup\$
0
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
I discovered that array destructing has the capability of providing default values.
const [, id = '', text = ''] = match;
return { id, text };
answered Aug 3, 2018 at 13:00
-
\$\begingroup\$ Only for
undefined
, not fornull
\$\endgroup\$Blindman67– Blindman672018年08月03日 14:40:42 +00:00Commented Aug 3, 2018 at 14:40
lang-js