Loops, and where your data lives

INPUT · Slides

Putting for and arrays together

01 / 05

Enter the strongest pairing

An array gives you "lots of data"; a for loop gives you "the power to repeat".

Put the two together and you can work through every item of an array in order. It is the pattern you will use more than any other in programming.

02 / 05

Build the index out of i

An array index is a number running 0, 1, 2, and so on.

Start the i of a for loop from 0 and fruits[i] gets you every item, in order.

let fruits = ["apple", "orange", "grape"];for (let i = 0; i < 3; i++) {  console.log(fruits[i]);}

Result

apple
orange
grape

03 / 05

Write the condition with length

Type the count in by hand and it breaks the moment the array grows.

Make the condition i < array.length and it runs over however many items there are. It is < and not <= because the last index is length - 1.

let fruits = ["apple", "orange", "grape", "peach"];for (let i = 0; i < fruits.length; i++) {  console.log(fruits[i]);}

Result

apple
orange
grape
peach

04 / 05

Use the items in a sum

An item you take out works in maths too. Combine it with the "piling variable" pattern and you get the total of an array.

This shape does test marks, household accounts and game scores alike. A real all-rounder.

let scores = [80, 65, 92];let total = 0;for (let i = 0; i < scores.length; i++) {  total = total + scores[i];}console.log(total);

Result

237

05 / 05

Combine i with the item

i is not only an index; you can show it as well.

"The nth something" is the basic form of a ranking or a list.

let members = ["Sakura", "Takeshi"];for (let i = 0; i < members.length; i++) {  console.log(i + 1 + ": " + members[i]);}

Result

1: Sakura
2: Takeshi