- Explain the three parts of a
forloop and write a counting loop - Choose
whilewhen the number of repetitions is unknown - Walk through a list with
for...ofand control a loop withbreakandcontinue
Imagine your teacher asks you to print every number from 1 to 100. You could write console.log 100 times, but that is tiring and easy to get wrong. Computers never get tired of repetition — you just need to tell them “do this 100 times” with a loop.
The for loop
When you know in advance how many times to repeat, the for loop is the best choice. Its parentheses hold three parts separated by semicolons:
- Start:
let i = 1— the counter is created. This runs only once, at the very beginning. - Condition:
i <= 5— checked before every repetition. As soon as it is false, the loop stops. - Step:
i++— changes the counter after every repetition.
for (let i = 1; i <= 5; i++) {
console.log(`Lap ${i}`);
}
for (let i = 10; i > 0; i -= 3) {
console.log('Countdown:', i);
}▸ Expected output
Lap 1 Lap 2 Lap 3 Lap 4 Lap 5 Countdown: 10 Countdown: 7 Countdown: 4 Countdown: 1
One run of the loop's body. A loop counting from 1 to 5 makes 5 iterations.
Calculate 1 + 2 + 3 + … + 100 with a loop.
Show solutionHide solution
sum variable at 0 to hold the total.On every iteration the loop adds the next
i to it: sum += i.When the loop ends,
sum = 5050 (run the code below).let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log('Sum:', sum);▸ Expected output
Sum: 5050
while and do...while
Sometimes we don't know how many repetitions we need. For example, Leyla has 50 manat and saves 20 manat every month. How many months until she can buy a 200-manat bicycle? A while loop repeats as long as its condition is true:
let savings = 50;
let months = 0;
while (savings < 200) {
savings += 20;
months++;
}
console.log(`${months} months, ${savings} AZN`);▸ Expected output
8 months, 210 AZN
A do...while loop checks its condition after the body, so the body runs at least once even if the condition is false from the start. In the example below the condition is false, but the message is still printed once.
let attempts = 5;
do {
console.log('Attempt number', attempts);
attempts++;
} while (attempts < 3);▸ Expected output
Attempt number 5
for...of: walking through a list
Very often a loop is written to do something with each item of a list. A list in square brackets is called an array — we will study it in its own lesson. The for...of loop takes the items of an array or a string one by one; no counter is needed.
const cities = ['Baku', 'Ganja', 'Shaki'];
for (const city of cities) {
console.log(`I want to visit ${city}`);
}
for (const letter of 'JS') {
console.log(letter);
}▸ Expected output
I want to visit Baku I want to visit Ganja I want to visit Shaki J S
break and continue
break stops the loop immediately, while continue skips only the rest of the current iteration and moves on to the next one. In the code below even numbers are skipped with continue, and break ends the loop once a number is greater than 7.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue;
}
if (i > 7) {
break;
}
console.log(i);
}▸ Expected output
1 3 5 7
break: it checks the items one by one and stops as soon as it finds the target.| Loop | When to choose it |
|---|---|
for | you know the number of repetitions or need a counter |
while | you don't know in advance how many repetitions there will be |
do...while | the body must run at least once |
for...of | you need to work with each item of an array or string |
Use a for loop to print the multiplication table of n from 1 to 5. Each line must look like this: 7 x 3 = 21.
const n = 7;
// print n x 1 = ... up to n x 5 = ...▸ Expected output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
Key points
- A
forloop has three parts: start, condition and step. whilerepeats while its condition is true;do...whilealways runs at least once.for...oftakes the items of an array or string one by one.breakstops the loop,continuejumps to the next iteration.- Forgetting to change the variable the condition depends on causes an infinite loop.
Check yourself
10 questions. Every correct answer earns XP.
for (let i = 0; i < 5; i++) repeat?