Skip to the content

Accumulators

JavaScript · Unit 3: Loops

To add up many numbers, create a variable with let at 0 before the loop.

On each round you add that round's number to it, and at the end it holds the total.

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

Prints

10

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Predict the output

    What does this code print?

  3. 3. Find the bug

    This program should add up the three grades the person types. Which line has the error?

  4. 4. Complete the code

    Complete this to add up the numbers from 1 to 5.

  5. 5. Predict the output

    What does this code print?

  6. 6. Predict the output

    How many rounds does this code count?

  7. 7. Predict the output

    What does this code print?

  8. 8. Put the lines in order

    The person types four grades. Put the lines in order to count how many are passing (60 or more).

  9. 9. Find the bug

    This program should print the multiples of 5 from 1 to 20 and say how many there are. Which line has the error?

  10. 10. Complete the code

    Complete this to work out 1 x 2 x 3 x 4.

  11. 11. Write the code

    Write sumUpTo(n), which returns the sum of all the numbers from 1 to n. For example, sumUpTo(4) gives 10.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →