JavaScript lesson · 16 min

JavaScript Loops

Repeat work over a list of values with a for...of loop and calculate a useful result.

Code runs locally in your browser

What you will practice

  • Use a for...of loop.
  • Accumulate a total value.
  • Calculate an average from a list.

What this means

A loop repeats the same block of code. This is useful when you have a list and want to do the same kind of work for every item.

`for...of` is a readable loop for arrays. It gives you one item at a time without making you manage index numbers manually.

Loops often build a result: a total, a filtered list, a rendered set of cards, or a report.

If this is your first time seeing this

A loop repeats code for multiple values. It is what you use when doing the same job by hand would be boring or fragile.

Read `for (const minutes of dailyMinutes)` as: take one value from the list, call it `minutes`, run the block, then move to the next value.

Mini glossary

Loop
Code that repeats while moving through values or while a condition stays true.
Iteration
One pass through a loop.
Accumulator
A variable that collects a running result, such as a total.

Example from everyday life

A loop is like checking every item on a packing list. You do the same action again and again: read the item, mark it, move to the next one, stop when the list is finished.

How it works step by step

  1. The code stores study minutes for several days in an array.
  2. `let total = 0` starts a running total.
  3. The `for...of` loop visits every number and adds it to `total`.
  4. After the loop, the code divides the total by the number of days to calculate an average.

Where you will use this

  • A table renders one row for every item in an array.
  • An analytics page adds daily numbers to calculate a weekly total.
  • A file tool processes every selected file one by one.

Before you run the code

Loops are the bridge between one example and many real records.

When you catch yourself copying the same line several times for similar values, a loop is often the cleaner answer.

Common beginner mistakes

  • Forgetting to initialize the total before the loop.
  • Changing the list while looping before you understand the consequences.
  • Using a loop when `map`, `filter`, or `reduce` would be clearer.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingAdds every value in the loop
WaitingCalculates the average

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Add another number to `dailyMinutes`.
  • Change the code to calculate the highest day value.
  • Print each day value inside the loop before adding it.