Loops, and where your data lives

INPUT · Slides

Choosing between the two loops

01 / 04

The same thing, written two ways

while and for are both tools for "do this repeatedly". The same result can be written either way.

The two below give exactly the same output. All that differs is where the parts are kept.

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

Result

1
2
3
1
2
3

02 / 04

A rough guide to choosing

If you are unsure, think of it this way.

  • the number of laps is settled up frontfor (three times, ten times, once per item)
  • you do not know the number; it depends on a conditionwhile (until the total passes 100, until the stock runs out)

When either would do, for is often the easier read.

let money = 100;let days = 0;while (money >= 30) {  money -= 30;  days++;}console.log(days);

Result

3

03 / 04

Mind the boundary of the condition

i <= 5 and i < 5 differ by one lap. This is a very easy thing to get wrong.

  • let i = 1; i <= 5 … 1,2,3,4,5, so five laps
  • let i = 1; i < 5 … 1,2,3,4, so four laps
  • let i = 0; i < 5 … 0,1,2,3,4, so five laps

The third shape comes up a lot when you learn arrays soon, so keep it somewhere in the back of your mind.

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

Result

0
1
2
3
4

04 / 04

The pitfalls they share

Whichever way you write it, the things to watch are the same.

  • always move the variable used in the condition. Leave it still and it never ends
  • keep the piling variable outside the repetition
  • say the boundary out loud once (is it < or <=?) to check it

Firm all of this up with the practice, then on to arrays.