Computers are good at doing the same thing many times. A loop repeats a block of code.
The for loop
The for loop is the one to use when you know how many times to repeat:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
That prints 1, 2, 3, 4, 5. The brackets hold three parts, separated by semicolons:
let i = 1runs once, at the start. It creates a counter.i <= 5is checked before every round. The loop continues while it is true.i++runs after every round. It adds 1 to the counter.
Programmers traditionally call the counter i.
Building up a result
A very common pattern is to create a variable before the loop and update it inside:
let total = 0;
for (let i = 1; i <= 4; i++) {
total += i;
}
console.log(total); // 1 + 2 + 3 + 4 = 10
The while loop
A while loop repeats as long as its condition is true. Use it when you do not know in advance how many rounds it will take:
let coins = 50;
while (coins >= 15) {
coins -= 15;
}
console.log(coins); // 5
Something inside the loop must eventually make the condition false. Otherwise the loop never ends. If that happens here, the editor stops your code after a few seconds and tells you.
Your Task
- Use a
forloop to print the numbers from 1 to 10, one per line. - In the same loop, add each number to
sum. - After the loop, print
sum.
- The code uses a
forloop - The numbers 1 to 10 are printed in order, one per line
sumends up as55- The sum is printed after the loop
Lesson complete!
Next Lesson: Functions