Loops, and where your data lives

INPUT · Slides

Repeating with while

01 / 06

Lining up the same line is painful

All you want is 1 through 5 on the screen, and yet it takes five console.log lines. Up to 100 and it is simply not on.

This is what a computer is good at: doing the same thing again and again. Let it.

02 / 06

The shape of while

Write while (condition) { work } and the inside of { } keeps repeating for as long as the condition holds.

The moment it stops holding, the repetition ends and you move on to the next line.

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

Result

1
2
3

03 / 06

Following it round one lap at a time

Here is the order the code above runs in.

  • i is 1. The condition 1 <= 3 holds → show 1, make i 2
  • The condition 2 <= 3 holds → show 2, make i 3
  • The condition 3 <= 3 holds → show 3, make i 4
  • The condition 4 <= 3 does not hold → done

The thing to notice is that it goes and looks at the condition at the start of every lap.

04 / 06

Forget the update and it never ends

What if you took i++ out of that code? i would stay 1 forever, so the condition i <= 3 would hold forever.

Which is to say it would never end. That is called an infinite loop. When your screen freezes, suspect this.

Once you have written a while, always move the variable used in the condition inside the { }. Remember only that and you will be fine.

05 / 06

You can count down too

You do not have to go up. You can also go down until the condition stops holding.

What matters is that the condition stops holding at some point.

let count = 3;while (count > 0) {  console.log(count);  count--;}console.log("go");

Result

3
2
1
go

06 / 06

Piling up a total

Set a variable up outside the repetition and add to it inside the { }, and you get a total.

This "variable you pile into" shape turns up forever from here on, so get your hands moving on it properly now.

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

Result

15