Loops, and where your data lives

INPUT · Slides

Repeating with for

01 / 06

Three parts, scattered about

When you counted with while, you always wrote the same three things.

  • the start (let i = 1) … before the repetition
  • the condition to carry on (i <= 3) … in the brackets of while
  • the update (i++) … inside the { }

Because those three sit apart from each other, it is easy to forget the update.

02 / 06

for gathers them onto one line

for is the way of writing it that lines the three parts up inside the brackets, separated by ;.

The shape is for (start; condition; update) { work }.

for (let i = 1; i <= 3; i++) {  console.log(i);}

Result

1
2
3

03 / 06

It runs in the same order as while

Only the writing changed; what happens is exactly what while did.

  • the start runs once, at the beginning
  • the condition is looked at at the start of every lap. If it does not hold, that is the end
  • after the inside of { } runs, the update runs

Because the update sits in the brackets, it is harder to forget. That is the good thing about for.

04 / 06

Using i in a sum

i is not just a number to show. Use it in a sum and you get a different result every lap.

for (let i = 1; i <= 4; i++) {  console.log(`4 x ${i} = ${4 * i}`);}

Result

4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16

05 / 06

Piling up a total

Putting the variable you pile into outside is the same as with while.

Make it with let inside the for and it gets built again from scratch every lap, so watch out for that.

let total = 0;for (let i = 1; i <= 5; i++) {  total += i;}console.log(total);

Result

15

06 / 06

Write it to learn it

for is the most used way of writing a repetition with a set number of laps. It will turn up again and again from here.

Start by just tracing the shape.