Loops Lesson

A loop repeats a block of code. Loops are useful when the same action needs to happen multiple times, especially when working with a list of values. Instead of writing the same command over and over, the loop handles the repetition.

A common loop pattern is a running total. The program starts with zero, visits each value, and adds that value into the total. This works for scores, prices, distances, and many other collections of numbers.

The loop visits each score in order. If the array grows, the same loop still works because it uses scores.length instead of a fixed number.

Code Runner Challenge

Loops Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Loops Lesson

const scores = [12, 18, 9, 24];
let total = 0;

for (let i = 0; i < scores.length; i++) {
  total = total + scores[i];
}

console.log("Total score: " + total);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

The concept matters because it turns a vague programming word into a real move the code can make. The sample below keeps the situation small enough to follow.