JavaScript Basics · Lesson 6 of 13

Loops

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:

  1. let i = 1 runs once, at the start. It creates a counter.
  2. i <= 5 is checked before every round. The loop continues while it is true.
  3. 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

  1. Use a for loop to print the numbers from 1 to 10, one per line.
  2. In the same loop, add each number to sum.
  3. After the loop, print sum.
  • The code uses a for loop
  • The numbers 1 to 10 are printed in order, one per line
  • sum ends up as 55
  • The sum is printed after the loop