JavaScript Basics: Make Web Pages Come Alive · Lesson 4 of 8

Lesson 4: Loops: Repeating Work

Repeat code with for and while loops, and control them with break and continue.

Lesson 4: Loops: Repeating Work

The for loop

A for loop has three parts: where to start, when to keep going, and how to move on.

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Output:

1
2
3
4
5

i++ means "add 1 to i". A multiplication table:

for (let i = 1; i <= 5; i++) {
  console.log(`7 x ${i} = ${7 * i}`);
}

Output:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

Adding up

let total = 0;
for (let n = 1; n <= 10; n++) {
  total += n;
}
console.log(total);

Output:

55

The while loop

let count = 3;
while (count > 0) {
  console.log(count);
  count--;
}
console.log("Go!");

Output:

3
2
1
Go!

A while loop must eventually make its condition false. If it never does, it runs forever and freezes the page.

break and continue

for (let n = 1; n < 10; n++) {
  if (n % 2 === 0) continue;
  if (n > 7) break;
  console.log(n);
}

Output:

1
3
5
7

Try it yourself

  1. Print the even numbers from 2 to 20.
  2. Add up the numbers 1 to 100.
  3. Print a countdown from 10 to 1.

Next lesson: arrays and objects.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 4: Loops: Repeating Work | MeroSir