01 / 06
Loops, and where your data lives
INPUT · Slides
Repeating with while
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.
iis1. The condition1 <= 3holds → show1, makei2- The condition
2 <= 3holds → show2, makei3 - The condition
3 <= 3holds → show3, makei4 - The condition
4 <= 3does 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