Count Totals and Characters With for

In the video, you packed a while loop into a for header and followed it one pass at a time. Your rounds loop logged Round 1, Round 2, and Round 3. The countdown went 3, 2, 1, and the score climbed in steps of 10. Each pass printed a line, and that was the whole job.

Most loops do more than print. They collect something along the way, like a running score, or they visit the letters of a word one by one. In this lesson, you’ll write for loops that add up a total and that walk through the characters of a string. Both are skills you’ll practice in the coding exercise that follows.

Add Up Points Across Rounds

Rounds and points show up in plenty of games. Say a quiz night runs in rounds, and later rounds are harder, so each round is worth as many points as its number. Round 1 gives 1 point, round 2 gives 2 points, and so on. How many points does a player who wins all five rounds collect in total?

You could add 1 + 2 + 3 + 4 + 5 by hand. However, the quiz might have five rounds tonight and twenty next week, so a loop that adds them for you is more useful. Save this as points.js in your course folder:

Language: JavaScript Filename: points.js
let total = 0;

for (let round = 1; round <= 5; round++) {
  total = total + round;
}

console.log("Total points:", total);

Before you run it, predict the number it prints. Then give it a spin:

Language: Shell
$ node points.js
Total points: 15

The variable total is an accumulator, a variable that collects a result across the passes of a loop. Each line of the program has its place:

  • Before the loop: total starts at 0, once. Nothing has been added yet.
  • In each pass: total = total + round adds this round’s points to what’s already there.
  • After the loop: console.log() reports the result once, after every round’s points have been added.

Here’s how total grows. Each row shows the values during one pass:

round total before the body total after the body
1 0 1
2 1 3
3 3 6
4 6 10
5 10 15

After the fifth pass, the update makes round equal to 6, the check 6 <= 5 is false, and the loop ends with 15 in total.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.