Loops, and where your data lives

INPUT · Slides

Taking one item out of an array

01 / 06

You want to use just one of them

You can show the whole array, but what you usually want is one of the things inside — "just show me the second fruit", say.

The items in an array have numbers on them, and naming the number gets you the item.

02 / 06

The numbering starts at 0

Write [number] after the array and you get the value at that position. That number is called the index.

The thing to watch is that it starts at 0, not 1. The first is 0, the second is 1, the third is 2.

const fruits = ["apple", "orange", "peach"];console.log(fruits[0]);console.log(fruits[2]);

Result

apple
peach

03 / 06

What comes out is an ordinary value

Once it is out, you can forget it came from an array. It is just a string, just a number.

You can do maths with it, and you can drop it into a template literal.

const scores = [80, 95, 60];console.log(scores[0] + scores[1]);console.log(`the first one is ${scores[0]}`);

Result

175
the first one is 80

04 / 06

The number can be a variable

Here is the important bit. Inside [ ] you can write a variable, not only a number.

Which means that changing the variable changes where you take from. Once this meets repetition in the next lesson, it gets powerful very quickly.

const colors = ["red", "blue", "yellow"];let i = 1;console.log(colors[i]);i++;console.log(colors[i]);

Result

blue
yellow

05 / 06

A number out of range gives undefined

What happens if you name a number the array does not have? It does not error — it gives back undefined (no value).

This happens when you index past the end, like the fourth item of a 3-item array. Since nothing errors and stops you, it is an easy bug to miss.

const fruits = ["apple", "orange", "peach"];console.log(fruits[3]);console.log(fruits[100]);

Result

undefined
undefined

06 / 06

Taking the last item

To grab "the last one", counting the items by hand every time is tedious. An array's .length tells you how many items there are, so length - 1 is the last index.

Because the first is 0, the last index is one less than the count.

const fruits = ["apple", "orange", "peach"];console.log(fruits.length);console.log(fruits[fruits.length - 1]);

Result

3
peach