Computer Science · Chapter 1 · Writing Code
How to tell a computer to do something many times — without writing it out many times.
bookSHelf · Introduction to Computer Science · §1.2 · a self-paced section
By the end of this section you will be able to
01
See what a loop is and why it beats copy-paste.
02
Write a for loop — init, condition, update.
03
Write a while loop, and know when to use each.
04
Loop over the items of a list.
05
Count and accumulate — a sum, a max, a tally.
06
Nest loops and dodge the common pitfalls.
The opening problem — doing the same thing over and over
The hard way — copy and paste
console.log("hello"); console.log("hello"); console.log("hello"); console.log("hello"); console.log("hello");
Five lines. Now imagine a thousand.
The loop way — say it once, repeat it
for (let i = 0; i < 5; i++) { console.log("hello"); }
Three lines — and changing 5 to 1000 is a one-character edit.
The idea in one sentence
Definition — loop
A loop is an instruction that runs the same block of code again and again — until a condition tells it to stop.
The body and the repeat
The code inside the braces is the body. The loop runs the body, checks whether to keep going, and if so runs it again. Each pass is one iteration.
Every loop, underneath, answers three questions
Where do I start? Should I keep going? What comes next?
The for loop packs all three questions into one line
A counting loop — prints 0, 1, 2, 3, 4
for (let i = 0; i < 5; i++) { console.log(i); }
Three parts, in order
Follow the counter, one pass at a time
The loop
for (let i = 1; i <= 5; i++) { console.log(i); }
Read across each row: check the condition, run the body, then update.
Table 1.2.1 — the trace
| pass | i | i ≤ 5? | prints |
|---|---|---|---|
| 1 | 1 | yes | 1 |
| 2 | 2 | yes | 2 |
| 3 | 3 | yes | 3 |
| 4 | 4 | yes | 4 |
| 5 | 5 | yes | 5 |
| 6 | 6 | no | — stop |
When you don't know the count in advance
Double until past 100
let n = 1; while (n <= 100) { n = n * 2; } console.log(n); // 128
When to reach for while
A while loop just repeats while a condition holds — no counter required. Use it when the number of passes depends on what happens inside the loop, like "keep doubling until we pass 100."
Same idea, two shapes — pick by what you know
Reach for for when…
…you know how many times, or you're stepping a counter over a range or a list — "do this for each i from 0 to n−1." The count is built into the loop header.
Reach for while when…
…you'll stop on a condition, not a count — "until the user quits," "until the number is small enough." You may loop zero times, or many.
Two words that change the flow
break — leave the loop now
for (let i = 1; i <= 10; i++) { if (i === 5) break; console.log(i); // 1 2 3 4 }
continue — skip to the next pass
for (let i = 1; i <= 5; i++) { if (i % 2 === 0) continue; console.log(i); // 1 3 5 }
The most common job a loop does
Visit every item
let fruits = ["apple", "pear", "plum"]; for (let i = 0; i < fruits.length; i++) { console.log(i + ": " + fruits[i]); }
Or, shorter: for (let f of fruits) { … }
Output
0: apple 1: pear 2: plum
The counter i doubles as the item's position (its index).
Try it now — trace it in your head first
Try It Now 1 — a counter that goes down
for (let i = 3; i > 0; i--) { console.log(i); } console.log("go!");
The counter starts at 3 and steps down while it stays above 0.
3, 2, 1, go!
A countdown. When i hits 0 the condition i>0 is false, so the loop stops — then the last line runs.
The pattern behind almost every useful loop
Worked Example 1.2.1 — add up a list
let nums = [4, 8, 15, 16, 23, 42]; let total = 0; for (let x of nums) { total += x; } console.log(total); // 108
Start an accumulator at 0, then add each item as the loop visits it.
Keep a variable outside the loop
total lives outside so it survives every pass; the body just grows it. Sum, product, max, count — all follow this same shape.
Same shape, different job
Worked Example 1.2.2 — the running max
let nums = [4, 8, 15, 16, 23, 42]; let max = nums[0]; for (let x of nums) { if (x > max) max = x; } console.log(max); // 42
Guess the first item is biggest, then let the loop correct you.
Remember the best so far
Each pass compares one item to the current champion and updates if it's bigger. After the last item, max holds the winner.
Counting only the items that match
Worked Example 1.2.3 — how many are even?
let nums = [4, 8, 15, 16, 23, 42]; let evens = 0; for (let x of nums) { if (x % 2 === 0) evens++; } console.log(evens); // 4
A tally is a sum that only counts the hits.
Add an if inside the loop
The loop visits every item; the if decides which ones count. Here 4,8,16,42 are even — four of them.
What a loop can total in the blink of an eye
5050
the sum 1+2+⋯+100, computed by a loop in exactly 100 steps — one addition per pass.
1+2+⋯+100=2100⋅101=5050.
The loop doesn't need the formula — it just adds one number at a time. But it's a nice check that the loop and the arithmetic agree.
A loop inside a loop
Rows and columns
for (let r = 1; r <= 3; r++) { for (let c = 1; c <= 3; c++) { console.log(r, c); } }
The inner loop runs in full, every time
For each pass of the outer loop, the inner loop runs start to finish. Three outer passes × three inner passes = nine lines. Nested loops are how we handle grids, tables, and pairs.
A concrete nested-loop example
Build each row, then print it
for (let r = 1; r <= 3; r++) { let row = ""; for (let c = 1; c <= 3; c++) { row += (r * c) + " "; } console.log(row); }
Output
1 2 3 2 4 6 3 6 9
Outer loop = the row; inner loop = the columns across that row.
The inner count can depend on the outer counter
One more star each row
for (let r = 1; r <= 4; r++) { console.log("*".repeat(r)); }
Output
* ** *** ****
Row r prints r stars — the shape grows with the counter.
Try it now — add them up
Question. The triangle loop runs rows 1 through 4, printing r stars on row r. How many stars does it print in total?
10 stars
Row by row that's 1+2+3+4=10. Extend it to 10 rows and you'd print 1+2+⋯+10=55 — the same running-sum pattern from earlier.
The most common loop bug of all
Bug — runs one time too many
let a = [10, 20, 30]; for (let i = 0; i <= a.length; i++) { console.log(a[i]); // ...30, undefined }
Indexes are 0,1,2 — but i≤3 also tries a[3], which doesn't exist.
Fix — stop before the length
let a = [10, 20, 30]; for (let i = 0; i < a.length; i++) { console.log(a[i]); // 10, 20, 30 }
Use <, not <=, when looping to length.
A loop that never ends
Bug — the counter never moves
let i = 0; while (i < 5) { console.log(i); } // i stays 0 — forever
Fix — make progress toward the exit
let i = 0; while (i < 5) { console.log(i); i++; // now it reaches 5 and stops }
Every loop needs a reason to stop: a counter that advances, or a condition that eventually turns false. Forget it and the program hangs.
Try it now — read carefully before you decide
Try It Now 3 — sum 1 through 10?
let sum = 0; for (let i = 1; i < 10; i++) { sum += i; } console.log(sum);
It looks like it sums 1 through 10 — but read the condition.
Off by one — it stops at 9
i < 10 never lets i reach 10, so it prints 45, not 55. Use i <= 10.
Try it live — edit the code and run it, right here
Editor — a loop that sums 1..n, then draws a triangle
Output — console.log appears here
▶ Press Run to see the output…
Everything you just learned, in one breath
Conclusions
The core idea
A loop trades repetition for a tiny bit of bookkeeping — a counter or a condition. Once you can read the three parts of a loop, most real programs stop looking mysterious.
Keep practising
The Try It Live editor is yours — change n, print a bigger triangle, sum only the odd numbers. The fastest way to trust a loop is to run it.
You can now write for and while loops, loop over lists, accumulate results, nest loops, and avoid the classic bugs. Next: §1.3 Functions — packaging code you can reuse. Back to start.