Computer Science · §1.2

Paper

Loops

How to tell a computer to do something many times — without writing it out many times.

The opening problem

// the hard way is five lines — the loop way is three:
for (let i = 0; i < 5; i++) {
  console.log("hello");
}

Changing 5 to 1000 is a one-character edit — not a thousand more lines.

Definition — loop

Repeat until told to stop.

The code inside the braces is the body. The loop runs it, checks whether to keep going, and repeats. Each pass is one iteration.

The for loop — three parts

for (let i = 0; i < 5; i++) {
  console.log(i);   // 0 1 2 3 4
}

init starts the counter · condition keeps it going · update steps it after each pass.

A loop visits each element

index i 4 8 15 16 23 0 1 2 3 4

The counter i doubles as each item's position — its index, 0 to 4.

Accumulate — a running total

index i total 4 8 15 16 23 0 1 2 3 4 4 12 27 43 66

Start a total at 0, then add each item as the loop visits it → 66.

Same idea, two shapes

for or while?

for — when you know the count, or you're stepping a counter over a range or a list.

while — when you stop on a condition: until the user quits, until it's small enough.

Pitfall — off by one

for (let i = 0; i <= a.length; i++)  // a[3] → undefined
for (let i = 0; i <  a.length; i++)  // 10, 20, 30 ✓

Indexes run 0, 1, 2 — so use <, not , when looping to length.

Recap — in one breath

Body · stop · accumulate.

A loop repeats a body until a condition stops it; an accumulator kept outside the loop sums, maxes, or tallies as it goes.

§1.2 — conclusion

A loop trades repetition for a little bookkeeping — a counter or a condition.