How code is written today

INPUT · Slides

Taking things out of an array

01 / 05

Where you were taking things out by number

To take a value out of an array you have written the number, as in ranking[0]. Two lines if you want the top two as variables.

The same as with objects: near-identical lines in a row. And shift one number by one and a different person quietly goes in.

const ranking = ["Yui", "Haruto", "Minato"];const first = ranking[0];const second = ranking[1];console.log(first);console.log(second);

Result

Yui
Haruto

02 / 05

Put [ ] on the left of the =

This time you write [ ] on the left of the =. Line up variable names inside and the array's contents get handed out from the front in order.

The shape looks a lot like the object one, but the symbol is [ ] instead of { }. The difference is whether the clue for taking things out is "the name" or "the order".

const ranking = ["Yui", "Haruto", "Minato"];const [first, second] = ranking;console.log(first);console.log(second);

Result

Yui
Haruto

03 / 05

You decide the names

This is the big difference from objects. An array's items have no names; they are settled by position alone. So the names of the catching variables are yours to choose freely.

In exchange, you have to know yourself "which position is what". Give them names that fit the contents.

const colors = ["red", "blue"];const [main, sub] = colors;console.log(main);console.log(sub);

Result

red
blue

04 / 05

You can skip positions you do not want

Sometimes you only want the third one. For that, write no variable name and put just a , and you skip that position.

But ,s in a row are hard to count. Keep the skipping to one or two; beyond that, taking it by number reads better.

const ranking = ["Yui", "Haruto", "Minato"];const [, , third] = ranking;console.log(third);

Result

Minato

05 / 05

Not enough means undefined

Line up more variables than there are items and it does not error. The spare variables get undefined.

The same as writing a name that is not there with an object. Remember that not enough goes quietly on.

Right — let us take things out in order.

const pair = ["left", "right"];const [first, second, third] = pair;console.log(third);

Result

undefined