Imagine adding 100 stories to a page, one line of code each. Loops let you write the steps once and repeat them as many times as you need.
flag
What you'll learn
How to repeat code a set number of times with for.
How to repeat while something is true with while and do...while.
How to go through every item of an array with for...of, and how to stop early with break.
waving_handWelcome to loops
A loop runs the same block of code again and again. Each time through is called a round, or an iteration.
Every loop needs a way to stop, usually a condition like the ones in JS Lesson 3. When the condition becomes false, the loop ends and the code after it runs.
Loops and arrays go well together: one loop can visit every item of a list, no matter how long it is.
directions_run
Think of P.E. class. "Run 5 laps" is a for loop: you know the count before you start.
"Keep jogging while the whistle hasn't blown" is a while loop: you check before each lap.
"Check each classmate's name on the list" is a for...of loop. And "stop once everyone is here" is break.
directions_runRun 5 lapsYou know how many times before you start.for (let lap = 1; lap <= 5; lap++)
local_drinkFill a glass while it isn't fullYou check first, then pour again.while (glass < 250)
ramen_diningTaste the soup, then add salt while it's blandYou always taste at least once.do { } while (bland)
eggCheck each egg in the trayOne egg at a time, until the tray is done.for (const egg of tray)
keyStop looking once you find your keysNo need to check the other pockets.break;
Now let's see the code ↓
directions_runRun 5 lapsYou know how many times before you start.for (let lap = 1; lap <= 5; lap++)
local_drinkFill a glass while it isn't fullYou check first, then pour again.while (glass < 250)
ramen_diningTaste the soup, then add salt while it's blandYou always taste at least once.do { } while (bland)
eggCheck each egg in the trayOne egg at a time, until the tray is done.for (const egg of tray)
keyStop looking once you find your keysNo need to check the other pockets.break;
for is for a known number of rounds, while and do...while are for "until something changes", and for...of is for lists.
searchA closer look
The three parts of a for loop
forkeyword
let lap = 1;start (runs once)
lap <= 5;condition (keep going?)
lap++step (after each round)
lap++ is a short way to write lap = lap + 1. lap-- takes 1 away. The counter is often named i, short for index.
while and do...while
while checks its condition before each round, so if the condition is false at the start, the block never runs.
do...while checks after each round, so its block always runs at least once.
for...of: one item at a time
for (const topic of topics) reads like a sentence: "for each topic of the topics list". Each round, topic holds the next item.
You don't need a counter or topics[i], so there's less to get wrong.
Loops that never end
If the condition never becomes false, the loop runs forever and the page freezes. This is called an infinite loop.
It usually happens when you forget to change the counter, like a while loop without readers = readers * 2.
In WebCore, a loop that runs for too long is stopped for you, and the console says A loop ran for too long. In a normal browser, the tab would just stop responding.
constructionLet's build it
Let's fill the Front Page Bytes topic list with loops. The HTML and CSS stay the same in every step: a heading and an empty list, <ul id="list">.
Some steps add items to the list, and others write to the console.
1Step 1: Repeat a set number of times with for
Your code
for (let lap = 1; lap <= 5; lap++) { console.log("Lap " + lap);}console.log("Done running!");
lap starts at 1. Before each round, the loop checks lap <= 5, and after each round, lap++ adds 1.
So the console shows Lap 1 to Lap 5. When lap becomes 6, the condition is false, the loop ends, and line 4 runs.
This time the counter i starts at 0, the first index, and stops before topics.length, which is 3.
Each round uses topics[i] with the steps from JS Lesson 1: make an <li>, fill it, append it. Three lines inside the loop make three list items.
The readers count doubles each round: 2, 4, 8, and so on. while checks readers < 100 before each round. After 128, the check is false, so the loop ends.
Here, you didn't know the number of rounds before you started. That's when while is the right choice.
5Step 5: Run at least once with do...while
Your code
let tries = 10;do { console.log("Try number " + tries); tries++;} while (tries < 3);
tries is 10, so tries < 3 is false from the start. A while loop would never run. But do...while runs the block first and checks afterwards, so the console shows Try number 10 once.
The ; after for ( ) ends the loop right there, so the loop repeats nothing. The { } below is no longer part of it.
It runs once on its own, where lap doesn't exist, so the console shows lap is not defined.
tips_and_updatesTip: Start the block { right after the closing parenthesis of for ( ), with no semicolon between them.
There's only one <li>, made before the loop. Each round changes its text and appends the same element again, which only moves it. So the list shows just one item: the last one, Apps.
tips_and_updatesTip: Make a new element inside the loop, so every round gets its own.
quizTest your knowledge
Write JavaScript in the JS tab. The fruits array is ready for you. If a loop runs forever by mistake, WebCore stops it after a moment and says so in the console.
auto_awesomeNo clicking needed. Each goal gets a check mark by itself once your code does it.
Use a for loop with a counter, like one that logs 1 to 5.not done yet
Use for...of to go through the fruits array.not done yet
Add every fruit to #list as its own <li>.not done yet