Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can I use as placeholders in es6 array destructuring?

I don't like the , , here:

let colors = [ "red", "green", "blue" ];
let [ , , thirdColor] = colors;

Can I use some placeholders characters? I'd rather not introduce unused variables, I just want to make the code look clearer. Right now the only thing I can think about are comments:

let [/*first*/, /*second*/, thirdColor] = colors;

Any better ideas?

like image 316
mik01aj Avatar asked Jan 29 '16 14:01

mik01aj


1 Answers

There is no concept of a placeholder in JS. Often _ is used for this, but you can't actually use it more than once in one declaration:

let [_, secondColor] = colors; // OK
let [_, _, thirdColor] = colors; // error

Also, _ may actually be used in your code, so you'd have to come up with another name, etc.

The simplest way may be to access the third element directly:

let thirdColor = colors[2];
let {2: thirdColor, 10: eleventhColor} = colors;
like image 65
Felix Kling Avatar answered Nov 15 '22 13:11

Felix Kling