Loops, and where your data lives

INPUT · Slides

Taking one item out of an array

01 / 04

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 / 04

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 / 04

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 / 04

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