Loading

T4 JavaScript · Lesson 6

Loops

Doing a job again and again: the for loop and its three parts, while and do...while, for...of over arrays and strings, break and continue, the patterns that loops are used for, and the array methods forEach, map, filter, reduce, some and every.

  • write a for loop, and say where it starts, when it stops and how it steps
  • write a while loop for a job whose number of rounds is not known in advance, and avoid a loop that never ends
  • walk through an array or a string with for...of
  • stop a loop early with break, and skip a round with continue
  • use the common patterns: a running total, a count, the largest item, a search
  • do the same jobs with forEach, map, filter, reduce, some and every
About 70 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06)Play this lesson's games

The back cover

A computer's great gift is patience: it will do the same small job a thousand times without tiring or slipping. A loop is how you ask it to. Written well, ten lines handle a list of ten items or ten lakh; written badly, they skip one, run one too many, or never stop.

These pages show the for loop and its three parts, while and do...while for jobs of unknown length, and for...of for every item in turn. They show break and continue, and the patterns most loops follow. They end with the array methods that do a loop's work in one line: forEach, map, filter and reduce.

Before you start

The story: Forty lamps, thirty-nine lit

At dusk the lamplighter's clockwork walks the Harbour Road, lighting its forty lamps one after another. Tonight it lit thirty-nine and stopped, and the last lamp, at the ferry steps, stayed dark. Last week it never stopped at all: it went on lighting lamps that were already lit until the oil ran out at midnight.

Master Hakim Verge opens its script. At its heart are four lines that say: start at the first lamp, light it, move on, and stop at the end.

"Every loop answers three questions," he says. "Where does it start? When does it stop? What moves it on? Get one of them wrong, and you get one of these two nights."

A program that can decide can do clever things once. A program that can repeat can do them a thousand times: add up every item of a bill, check every student's marks, light every lamp on a road. Writing the same line a thousand times is not the answer. A loop is: one block of code, run again and again, with something changing each time.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Comparisons.i <= 40 gives true or false.Every loop asks one to decide whether to go on.
++ and +=.i++, total += priceThey move a loop on, and add up as it goes.
Blocks and their scope.A let inside braces.Each round of a loop is a block.
Arrays and indexes.prices[0], prices.lengthLoops walk through arrays.
The last index.length - 1The cause of the most common loop slip.
if and else.if (m < 33) { ... }A loop often decides something about each item.
Callbacks.prices.find((p) => p > 100)map, filter and reduce take callbacks too.
find stops at the first match.Later items are not looked at.break does the same in a loop.
Template literals.`Round ${i}`A loop's round number in its output.
The remainder.i % 2 === 0 for an even number.Skipping every other round.

By the end of this lesson you will be able to:

  • write a for loop, and say where it starts, when it stops and how it steps;
  • write a while loop for a job whose number of rounds is not known in advance, and avoid a loop that never ends;
  • walk through an array or a string with for...of;
  • stop a loop early with break, and skip a round with continue;
  • use the common patterns: a running total, a count, the largest item, a search;
  • do the same jobs with forEach, map, filter, reduce, some and every.

How to follow this lesson

Every block on this page runs. To follow a loop, print the counter at the top of each round: console.log("round", i);. You then see exactly where the loop started, which rounds it ran and where it stopped, which is where most loop bugs hide. If a block ever runs for more than 3 seconds, the page stops it and says so; that is almost always a loop that never ends.

In one line

A loop runs the same block again and again, and every loop answers three questions: where does it start, when does it stop, and what moves it on?

The for loop

At a glance

A school's attendance register is read the same way every morning: start at roll number 1, call each name, and stop after the last. Nobody writes out a separate line for each child. A for loop is that routine written once.

Its head has three parts, for (start; condition; step). The start runs once, the condition is asked before every round, and the step runs after each. For an array, start at 0 and stop while the index is less than length, or you read one past the end.

Take a guess: For an array of 5 items, what is the last index a for loop should read?

A PT teacher says to the class: "Start at 1. Count out loud. Stop when you get past 10. Each time, take one step forward." Those instructions have three parts: where to start, when to stop, and how to move on. They are exactly the three parts of a for loop.

for loop

A loop written for (start; condition; step) { ... }. The start runs once. Then, before each round, the condition is asked: if it is truthy, the block runs, then the step runs, and the condition is asked again. When the condition is falsy, the loop ends.

for (let i = 1; i <= 3; i++) {
  console.log(`Round ${i}`);
}
Round 1
Round 2
Round 3

Read the brackets part by part. let i = 1 is the start: a counter named i, set to 1, made once. i <= 3 is the condition: "is i at most 3?". i++ is the step: add one to i after each round. The name i is a tradition, short for index; any name works.

Follow the counter. i is 1: 1 <= 3 is true, so Round 1 is printed, and i becomes 2. Then Round 2, and i becomes 3. Then Round 3, and i becomes 4. Now 4 <= 3 is false, so the loop ends. The block ran three times, and i reached 4 without a fourth round.

Iteration

One round of a loop. A loop that runs its block three times has three iterations; to iterate is to go round.

Starting at 0

Because indexes start at 0, most loops in real code start at 0 too, and stop with < rather than <=. A loop of i = 0; i < 3 runs for 0, 1 and 2, which is three rounds, and the program carries on after it:

for (let i = 0; i < 3; i++) {
  console.log(i);
}
console.log("done");
0
1
2
done

Counting down and stepping

The three parts can say anything. A countdown starts high, stops after 1, and steps down. A loop in fives steps by 5:

for (let i = 5; i >= 1; i--) {
  console.log(i);
}
console.log("Go!");
5
4
3
2
1
Go!
for (let i = 0; i <= 10; i += 5) {
  console.log(i);
}
0
5
10

Through an array, by index

A for loop over the indexes of an array reaches every item: start at 0, stop before the length, step by one. This is how to add up a bill:

const prices = [120, 45, 300];
let total = 0;
for (let i = 0; i < prices.length; i++) {
  total += prices[i];
}
console.log(total);
465

A common mistake

Writing <= where < belongs. With i <= prices.length, the last round reads prices[3], one past the end, and gets undefined. Added to a total it gives NaN; printed, it shows as undefined. This is called an off-by-one error, and it is the most common loop bug there is:

const prices = [120, 45, 300];
for (let i = 0; i <= prices.length; i++) {
  console.log(prices[i]);
}
120
45
300
undefined

The cure is a habit: for an array, start at 0 and use < with the length. The rule hides in the numbers: the indexes of three items are 0, 1 and 2, and 3 is the length, never an index.

Worked example 1

A temple's lamplighter lights lamps 1 to 40 along a road. Write the loop, and print only the first and the last lamp it lights, to check both ends.

What we have: lamps numbered 1 to 40

What we need: a loop that reaches 40 and stops there

The plan: start at 1, keep going while the lamp number is at most 40, step by one; print the lamp when it is 1 or 40

for (let lamp = 1; lamp <= 40; lamp++) {
  if (lamp === 1 || lamp === 40) {
    console.log(`Lit lamp ${lamp}`);
  }
}
Lit lamp 1
Lit lamp 40
  1. Lamps numbered from 1 need <= with the last number, 40. The condition is checked before every round, so the round for 40 runs, and 41 ends the loop.

It lights lamps 1 to 40, as the two printed lines show.

Check: 40 rounds: from 1 to 40, both included, is 40 − 1 + 1 = 40 lamps.

A path that fails: writing lamp < 40. The loop stops after lamp 39, and the last lamp stays dark: the night of the story.

When you are stuck: a for loop runs too many times, too few, or not at all

Print the counter at the top of each round to see where it starts and stops.

Check the condition against the last value you want: < length for indexes from 0, <= for numbers from 1.

If it never runs, the condition is false from the very start: try the first value by hand.

Check the step: it must move the counter towards the end, up for <, down for >.

Your turn

for (let i = 2; i <= 8; i += 2) {
  console.log(i);
}
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2
4
6
8
  1. Start at 2.
  2. Each round adds 2: 4, 6, 8.
  3. 10 is not at most 8, so the loop ends.

It prints 2, 4, 6, 8.

How many times does for (let i = 0; i < 5; i++) run its block?Tap to reveal
  1. i takes the values 0, 1, 2, 3 and 4.
  2. 5 < 5 is false, so there is no round for 5.

5 times.

Write a loop that prints 10, 20, 30 and 40.Tap to reveal
for (let n = 10; n <= 40; n += 10) {
  console.log(n);
}
10
20
30
40

Start at 10, stop after 40, step by 10.

Did you know?

Why the counter is called i

Loop counters are often called i, j and k, and the habit is older than JavaScript. In early Fortran there were no type declarations: variables whose name starts with I, J, K, L, M or N were whole numbers, and all others decimals. Fortran's own guide still notes that, without implicit none, variables are typed by the letter they begin with.

Why it fits here: It gives this topic's counter a history: in Fortran, a name starting with i was a whole number, just right for counting.

Sources: Wikipedia: Fortran; Fortran-lang: Variables

A loop with nothing in its head

Every part of a for loop's head is optional. MDN notes that all three expressions in the head of the for loop are optional, and the standard's grammar marks each one as optional. So for (;;) is a legal loop with no start, no condition and no step. It runs until a break inside it stops it.

Why it fits here: It shows what this topic's condition does: leave it out, and nothing ever tells the loop to stop.

Sources: MDN: for; ECMAScript Language Specification: The for Statement

In one line

A for loop is for (start; condition; step): the start runs once, the condition is asked before every round, and the step runs after each. For an array, start at 0 and stop with < length, or you read one past the end.

while: repeating until something changes

At a glance

A shopkeeper keeps weighing rice until the scale reads one kilo; nobody knows in advance how many scoops it will take. Some jobs repeat until something changes, not a fixed number of times. The scale decides when to stop.

A while loop asks its condition before each round, so it suits a job whose number of rounds is not known. A do...while asks after, so it runs at least once. Something inside the block must move the condition towards false, or the loop never ends.

Take a guess: How many times does a do...while loop run if its condition is false from the start?

A shopkeeper selling the last tickets for a show does not count rounds in advance. She sells one ticket, then another, for as long as any are left. A for loop suits a job with a known number of rounds. When the number is not known, and the loop must go on while something stays true, a while loop says so more plainly.

while loop

A loop written while (condition) { ... }. Before each round the condition is asked; while it is truthy, the block runs. Something inside the block must change, so that the condition becomes false one day.

let tickets = 3;
while (tickets > 0) {
  console.log(`Ticket sold, ${tickets - 1} left`);
  tickets--;
}
Ticket sold, 2 left
Ticket sold, 1 left
Ticket sold, 0 left

A while loop has the same three parts as a for loop, written in three places: the start, let tickets = 3;, before it; the condition in its brackets; and the step, tickets--;, inside the block. A for loop gathers all three in one line, which is why it is preferred whenever the rounds can be counted.

If the condition is false from the start, the block never runs, not even once:

let n = 10;
while (n < 5) {
  console.log("never");
}
console.log("skipped");
skipped

A loop that never ends

If nothing in the block moves the condition towards false, the loop asks the same question for ever. This is an endless loop, also called an infinite loop. It is the second night of the story, when the lamplighter never stopped. A program stuck in one does nothing else at all: a web page freezes, and a server stops answering.

This page will not let a block run for ever. If a block runs for more than 3 seconds, the page stops it and prints: Stopped: the code ran for more than 3 seconds (an endless loop, or a timer that never stops). If you see that message, look for the step: a loop whose counter never changes, or changes in the wrong direction.

A common mistake

Forgetting the step in a while loop. while (tickets > 0) { console.log(tickets); } never changes tickets, so the condition stays true for ever. Every while loop needs a line inside it that moves its condition towards false.

do...while: at least once

A do...while loop asks its question after each round, not before, so its block always runs at least once. It suits a job that must happen once before you can know whether to repeat it, such as asking for a PIN and checking it:

let tries = 0;
do {
  tries++;
} while (tries < 0);
console.log(tries);
1

The condition tries < 0 was false all along, yet the block ran once, because the question came after it.

Stopping from inside: while (true)

Sometimes the best place to decide to stop is in the middle of the block. A loop written while (true) never stops by itself, so it needs a break, which ends a loop at once, at the right moment. The next sections use break more; here it ends a loop after four rounds:

let i = 0;
while (true) {
  i++;
  if (i === 4) {
    break;
  }
}
console.log(i);
4
LoopAsks its questionUse it when
forbefore each roundthe rounds can be counted: from 1 to 40, or over the indexes of an array
whilebefore each roundthe loop goes on while something stays true, and the count is not known
do...whileafter each roundthe block must run at least once

Worked example 2

A savings jar starts with ₹500, and its owner adds ₹200 every month. Use a while loop to find how many months it takes to reach at least ₹2000.

What we have: a start of 500, a monthly 200, and a goal of 2000

What we need: the number of months

The plan: the number of rounds is what we want to find, so use while: keep adding while the jar is below 2000, and count each month

let jar = 500;
let months = 0;
while (jar < 2000) {
  jar += 200;
  months++;
}
console.log(months, jar);
8 2100
  1. Each round adds 200 and counts one month. After 7 months the jar holds 1900, still below 2000, so an eighth round runs, giving 2100.

It takes 8 months, and the jar then holds ₹2100.

Check: 500 + 8 × 200 = 2100, which is at least 2000, while 7 months would give 1900.

A path that fails: writing the condition as jar !== 2000. The jar goes 500, 700, ... 1900, 2100 and never equals 2000, so the loop never ends. Ask "below" with <, not "not equal".

When you are stuck: a while loop never ends, or never starts

Find the line inside the block that changes the condition. If there is none, add the step.

Check that the step moves towards false: a count going up for a condition with <.

Prefer < or > to !== in a loop's condition, so that a value that jumps past the goal still ends the loop.

If it never starts, print the condition just before the loop.

Your turn

let n = 1;
while (n < 20) {
  n *= 3;
}
console.log(n);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
27
  1. n goes 1, 3, 9: all below 20.
  2. 9 × 3 = 27, which is not below 20, so the loop ends.

It prints 27.

How many times does the block of do { x++; } while (false); run?Tap to reveal
  1. do...while asks after the round.
  2. So the block runs once, and then false ends the loop.

Once.

Why does let i = 0; while (i < 5) { console.log(i); } never end?Tap to reveal
  1. Nothing in the block changes i.
  2. i < 5 stays true for ever.

There is no step: add i++; inside the block.

Did you know?

No program can check every loop

No tool can check every loop for you. Alan Turing proved in 1937 that the halting problem is undecidable: no general algorithm can correctly decide, for every program and input, whether it finishes or runs forever. Simple cases are easy to decide, but more complex programs are not. Making sure that a loop ends stays the programmer's own job.

Why it fits here: It is why this topic insists that something inside the loop must move the condition towards false: no tool can promise it for you.

Sources: Wikipedia: Halting problem; Stanford Encyclopedia of Philosophy: Turing Machines

A loop nobody can prove will stop

Here is a while loop nobody can prove always stops. Start with any whole number; if it is even, halve it, and if it is odd, triple it and add one; repeat until you reach 1. Lothar Collatz introduced the idea in 1937. Computers have checked every starting value up to 271, and all reach 1, but no proof exists.

Why it fits here: It shows why this topic's warning is serious: whether a loop ends can be a question that even mathematicians cannot answer.

Sources: Wikipedia: Collatz conjecture; OEIS: A006577

In one line

A while loop asks its condition before each round, and suits a job whose number of rounds is not known; do...while asks after, so it runs at least once. Something inside the block must move the condition towards false, or the loop never ends.

for...of: every item, one by one

At a glance

A teacher handing back test papers goes down the pile one by one, without counting aloud. A for...of loop does the same: it visits each item in order, with no counter at all to get wrong.

It runs once for each item of an array, or each character of a string. When you need the position too, keep a count, or use a for loop. Do not confuse it with for...in, which gives an object's property names, not its values.

Take a guess: What does for...in give for an array: its items, or something else?

A ticket checker walking down a train does not think "seat 0, seat 1, seat 2". He goes from passenger to passenger until the coach ends. When a loop needs each item of an array, and not its index, there is a shorter loop that does exactly that.

for...of

A loop written for (const item of list) { ... }, which runs its block once for each item of the list, in order, with the item in the name given. Read it aloud as "for each item of list".

const cities = ["Pune", "Nagpur", "Nashik"];
for (const city of cities) {
  console.log(city);
}
Pune
Nagpur
Nashik

No counter, no condition, no step, and so no off-by-one error: the loop starts at the first item and stops after the last by itself. The name city is made fresh for each round, which is why it can be a const: within one round it never changes.

for...of works on anything that can be walked through item by item, which JavaScript calls an iterable. Arrays are iterable, and so are strings, whose items are their characters:

for (const letter of "chai") {
  console.log(letter);
}
c
h
a
i

The modern JavaScript step shows the other iterables, such as maps and sets, and how a for...of loop asks each one for its next item.

When you need the index too

for...of gives the items but not their positions. When a loop needs both, either use the for loop of the earlier section, or keep a count yourself:

const names = ["Asha", "Ravi"];
let place = 1;
for (const name of names) {
  console.log(`${place}. ${name}`);
  place++;
}
1. Asha
2. Ravi

The methods section below shows a third way: forEach hands its callback both the item and the index.

Not for...in

A common mistake

Writing for...in for an array. for...in is a different loop, made for the names of an object's properties, which the objects lesson teaches. On an array it gives the indexes, not the items, and gives them as strings:

const list = ["a", "b", "c"];
for (const i in list) {
  console.log(i, typeof i);
}
0 string
1 string
2 string

A way to remember which is which: for...of gives the items of the list; for...in gives the names in an object.

Worked example 3

A stationery shop's order lists the items bought: pen, notebook and geometry box. Print a line for each, numbered from 1, with the text Item 1: pen and so on.

What we have: an array of three items

What we need: a numbered line for each item

The plan: for...of for the items, and a count of our own for the numbers

const order = ["pen", "notebook", "geometry box"];
let n = 1;
for (const item of order) {
  console.log(`Item ${n}: ${item}`);
  n++;
}
Item 1: pen
Item 2: notebook
Item 3: geometry box

Three lines, from Item 1: pen to Item 3: geometry box.

Check: the count ends at 4 after three rounds, one more than the number of items.

Another way: a for loop over the indexes, printing `Item ${i + 1}: ${order[i]}`, gives the same lines; the + 1 turns an index from 0 into a number from 1.

When you are stuck: a for...of loop gives something unexpected

If it gives numbers in quotes instead of items, you wrote for...in. Use for...of.

If it gives single characters, the list was a string, not an array: check with Array.isArray.

If you need the position, keep a count, or use a for loop or forEach.

Print the list itself before the loop, to see what it really holds.

Your turn

let total = 0;
for (const n of [4, 5, 6]) {
  total += n;
}
console.log(total);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
15
  1. The loop gives 4, then 5, then 6.
  2. Each is added: 4 + 5 + 6 = 15.

It prints 15.

What does for (const ch of "Hi") { console.log(ch); } print?Tap to reveal
  1. A string's items are its characters.
  2. So the loop gives H, then i.

H, then i, on two lines.

Print every city of ["Delhi", "Agra"] in capitals, using for...of.Tap to reveal
for (const city of ["Delhi", "Agra"]) {
  console.log(city.toUpperCase());
}
DELHI
AGRA

DELHI and AGRA.

Did you know?

Names, not items

The for...in loop walks property names, and it has two surprises for arrays. MDN explains that it iterates over all enumerable string properties of an object, so for an array it gives the indexes as strings, "0", "1" and "2". And the standard says the mechanics and order of enumerating the properties is not specified, beyond a set of rules. For arrays, for...of is the safer loop.

Why it fits here: It explains this topic's warning not to confuse the two: for...in is built for an object's names, for...of for a list's items.

Sources: MDN: for...in; ECMAScript Language Specification: EnumerateObjectProperties

Not only for arrays

A for...of loop walks far more than arrays. MDN lists the iterable objects it accepts: Array, String, TypedArray, Map, Set, NodeList and other DOM collections, the arguments object, generators and user-defined iterables. So the NodeList that document.querySelectorAll gives back can be walked with for...of, item by item, with no counter at all.

Why it fits here: It widens this topic's loop: anything that can be listed, from the letters of a string to the elements of a page, can be walked the same way.

Sources: MDN: for...of; WHATWG: DOM Standard, NodeList

In one line

for...of runs once for each item of an array or string, in order, with no counter to get wrong. Keep a count, or use a for loop, when you need the position too, and do not confuse it with for...in, which gives an object's names.

break, continue, and loops inside loops

At a glance

A cashier counting notes stops at once on finding a torn one, and skips a note that is already marked. Loops need the same two moves: stop now, and skip this one. Both save work.

The keyword break ends the loop at once, and continue ends only the current round. Each acts on the innermost loop. A loop inside a loop runs its inner block once for every pair of rounds, which multiplies quickly on long lists. Ten rounds outside and ten inside make a hundred.

Take a guess: In a loop inside a loop, which loop does break end?

A teacher checking answer sheets for any failing mark can stop at the first one she finds: the question "did anyone fail?" is already answered. Another teacher, adding up marks, skips the sheets marked absent and carries on with the rest. Loops can do both.

break

A statement that ends the loop it is in at once. The program carries on after the loop.

continue

A statement that ends the current round of a loop at once. The loop carries on with its next round.

const marks = [45, 80, 20, 95];
for (const m of marks) {
  if (m < 33) {
    console.log("found a fail:", m);
    break;
  }
}
found a fail: 20

The loop looked at 45 and 80, found 20, printed it, and broke out. 95 was never looked at, which saves time in a long list. This is what find does inside, as the arrays lesson showed: it stops at the first match.

for (let i = 1; i <= 6; i++) {
  if (i % 2 === 0) {
    continue;
  }
  console.log(i);
}
1
3
5

For each even i, continue jumps straight to the next round, so the console.log below it is skipped. In a for loop, the step still runs after a continue, so i still goes up; that keeps the loop from getting stuck.

continue is often used to step over items that should not be counted. A list of fees in which 0 means "waived" counts only the real payments:

const fees = [500, 0, 300];
let paid = 0;
for (const f of fees) {
  if (f === 0) continue;
  paid++;
}
console.log(paid);
2

A common mistake

Using continue in a while loop before its step. In while (i < 5) { if (i === 2) continue; i++; }, the continue jumps back to the condition before i++ runs, so i stays 2 for ever, and the loop never ends. Put the step before any continue, or use a for loop, whose step always runs.

Loops inside loops

A loop's block can hold another loop. For each round of the outer loop, the inner loop runs all of its rounds. A times table is the classic case: for each row, go across the columns:

for (let row = 1; row <= 3; row++) {
  let line = "";
  for (let col = 1; col <= 3; col++) {
    line += `${row * col} `;
  }
  console.log(line.trim());
}
1 2 3
2 4 6
3 6 9

The outer loop ran 3 rounds, and in each the inner loop ran 3 rounds, so the multiplication ran 3 × 3 = 9 times. That multiplying is worth remembering: two loops of 1000 rounds each, one inside the other, run their inner block ten lakh times, which is why nested loops can be slow on big lists. The data structures and algorithms step measures this kind of cost.

break and continue act only on the loop they are written in. A break in the inner loop ends the inner loop, and the outer loop goes on with its next round.

Worked example 4

A cinema hall's seats are rows of seats, each either free or taken. Find the first free seat, and stop looking once it is found. Rows: A1 taken, A2 taken; B1 taken, B2 free.

What we have: a grid of seats, each with a name and whether it is taken

What we need: the name of the first free seat

The plan: loop over the rows and, inside, over the seats; when a free seat is found, note it and break out of both loops

const rows = [["A1", "A2"], ["B1", "B2"]];
const taken = ["A1", "A2", "B1"];
let found = null;
for (const row of rows) {
  for (const seat of row) {
    if (!taken.includes(seat)) {
      found = seat;
      break;
    }
  }
  if (found) break;
}
console.log(found);
B2
  1. The inner break ends only the seat loop. The second break, after it, ends the row loop as soon as found holds a seat.

The first free seat is B2.

Check: A1, A2 and B1 are in the taken list, and B2 is not.

A path that fails: writing only the inner break. With more rows, the outer loop would carry on to the next row and find another free seat, replacing the first.

When you are stuck: break or continue does not do what you expected

break ends the whole loop; continue ends only this round.

Each acts only on the loop it is written in, the innermost one.

In a while loop, put the step before any continue.

Print a line at the top of each round, to see which rounds really ran.

Your turn

for (let i = 1; i <= 5; i++) {
  if (i === 4) break;
  if (i === 2) continue;
  console.log(i);
}
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1
3
  1. i = 1 is printed.
  2. i = 2 is skipped by continue.
  3. i = 3 is printed.
  4. i = 4 breaks out of the loop, so 4 and 5 never print.

It prints 1 and 3.

How many times does the inner block run in for (let a = 0; a < 4; a++) { for (let b = 0; b < 5; b++) { ... } }?Tap to reveal
  1. The outer loop runs 4 rounds.
  2. Each time, the inner loop runs 5 rounds.
  3. 4 × 5 = 20.

20 times.

Print the numbers 1 to 10, skipping multiples of 3, with continue.Tap to reveal
for (let n = 1; n <= 10; n++) {
  if (n % 3 === 0) continue;
  console.log(n);
}
1
2
4
5
7
8
10

3, 6 and 9 are skipped.

Did you know?

A break that leaves two loops

A break can leave more than one loop. MDN explains that a labeled statement is any statement prefixed with an identifier, and that you can jump to the label with a break or continue nested within it. So outer: for (...) { for (...) { break outer; } } ends both loops at once. Labels are rare in everyday code, but they solve this one problem neatly.

Why it fits here: It adds one tool to this topic's break, which on its own ends only the innermost loop.

Sources: MDN: Labeled statement; ECMAScript Language Specification: Labelled Statements

A notation from 1894

How fast a loop's work grows has a notation older than computers. The symbol O was first introduced by the number theorist Paul Bachmann in 1894, and MacTutor calls him best known for his work in analytic number theory and for introducing the O-notation. Today a loop inside a loop over n items is called O(n2): double the list, and the work grows four times.

Why it fits here: It puts a name on this topic's warning that nested loops multiply: n rounds inside n rounds is n times n.

Sources: Wikipedia: Big O notation; MacTutor History of Mathematics: Paul Bachmann

In one line

break ends the loop at once, and continue ends only the current round; each acts on the innermost loop. A loop inside a loop runs its inner block once for every pair of rounds, which multiplies quickly on long lists.

The patterns loops are used for

At a glance

A shopkeeper adding up the day's sales keeps a running total on a slip: it starts at zero, each sale is added, and the total is read at closing time. The slip is the accumulator. Most loops work the same way.

They gather a result in an accumulator made before the loop. A total starts from 0, a count from 0, a largest from the first item, and text from an empty string. Each round changes it, and the result is read after the loop ends.

Take a guess: Why should a search for the largest number start from the first item, not from 0?

Most loops in real programs do one of a handful of jobs. Learn their shapes, and you will recognise them in any program, and write them without thinking. Each has a name kept outside the loop, set up before it starts, changed in each round, and read after it ends.

Accumulator

A name made before a loop and changed in each round, so that it gathers a result: a total, a count, the largest item so far, or text being built.

A running total

const prices = [120, 45, 300];
let total = 0;
for (const p of prices) {
  total += p;
}
console.log(total);
465

Start the total at 0, the value that changes nothing in a sum, and add each item. The total must be made outside the loop: made inside, it would be fresh in each round, as the scope lesson showed, and gather nothing.

A count

const words = ["tea", "coffee", "milk"];
let count = 0;
for (const w of words) {
  if (w.length > 3) {
    count++;
  }
}
console.log(count);
2

Start at 0, and add one only when the item passes the test: coffee and milk have more than 3 letters.

The largest, or the smallest

const marks = [72, 85, 90, 64];
let best = marks[0];
for (const m of marks) {
  if (m > best) {
    best = m;
  }
}
console.log(best);
90

Start with the first item as the best so far, then replace it whenever a bigger item comes along. Why not start at 0? Because a list of temperatures below zero, or of losses, would wrongly give 0 as its largest. Starting from a real item of the list is always safe, as long as the list is not empty.

Building text

+= joins strings, so a loop can build text a piece at a time. Starting from an empty string makes the whole result a string, even if the pieces are numbers:

let s = "";
for (let i = 1; i <= 5; i++) {
  s += i;
}
console.log(s, typeof s);
12345 string

A search

To find whether something is there, start with "not found", look at each item, and break when it turns up, as the cinema seats did. The arrays lesson's find and includes do this for you, and the next section shows more such methods.

PatternStart withIn each roundAfter the loop
total0add the itemthe sum
count0add one if the item passeshow many passed
largestthe first itemreplace it if the item is biggerthe largest
text""join a piecethe whole text
searchnull or falsenote the item and break, when foundthe item, or null

Worked example 5

A results portal has a student's marks in five subjects: 78, 92, 65, 88 and 71. Use one loop to find the total, the average, the highest mark and how many marks are 75 or above.

What we have: five marks

What we need: the total, the average, the highest, and a count

The plan: one loop with three accumulators, a total, a highest and a count, then the average from the total after the loop

const marks = [78, 92, 65, 88, 71];
let total = 0;
let highest = marks[0];
let good = 0;
for (const m of marks) {
  total += m;
  if (m > highest) highest = m;
  if (m >= 75) good++;
}
console.log(total, total / marks.length, highest, good);
394 78.8 92 3
  1. Each round feeds all three accumulators. The average needs the finished total, so it is worked out after the loop.

Total 394, average 78.8, highest 92, and 3 marks of 75 or more.

Check: 78 + 92 + 65 + 88 + 71 = 394, and 394 ÷ 5 = 78.8; the marks of 75 or more are 78, 92 and 88.

A path that fails: making total inside the loop. Each round would start it again at 0, and after the loop the name would not even exist.

When you are stuck: an accumulator gives the wrong result

Make it before the loop, not inside, or it starts again every round.

Check its starting value: 0 for a total or count, the first item for a largest, "" for text.

Print it at the end of each round, to see it grow.

If a total comes out as text, an item was a string: convert it with Number(...) as you add.

Your turn

let longest = "";
for (const w of ["ox", "tiger", "cat"]) {
  if (w.length > longest.length) longest = w;
}
console.log(longest);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
tiger
  1. longest starts empty, so ox, with 2 letters, replaces it.
  2. tiger, with 5, replaces ox.
  3. cat, with 3, does not replace tiger.

It prints tiger.

Why does let best = 0; give the wrong answer for the largest of [-5, -2, -9]?Tap to reveal
  1. No item is bigger than 0, so best is never replaced.
  2. The loop ends with 0, which is not even in the list.

Start with the first item, −5, instead.

Count the even numbers in [3, 8, 10, 7, 4] with a loop.Tap to reveal
let evens = 0;
for (const n of [3, 8, 10, 7, 4]) {
  if (n % 2 === 0) evens++;
}
console.log(evens);
3

3: 8, 10 and 4.

Did you know?

Where Math.max starts

The standard's own Math.max shows a safe starting point. Its steps begin with a largest value of minus infinity, then compare every argument with it in turn. So Math.max() with nothing to compare returns -Infinity, the starting value itself. Starting from 0 instead would give a wrong answer for a list of losses, where every number is negative.

Why it fits here: It is the reason for this topic's rule on largest values: start from something no real value can lose to, such as the first item.

Source: ECMAScript Language Specification: Math.max

Twenty accumulators

The word accumulator comes from early machines. ENIAC, built in the 1940s, was a large, modular computer, and twenty of its modules were accumulators that could add, subtract, and hold a ten-digit decimal number in memory. The University of Pennsylvania's account lists those twenty accumulators among the machine's memory. A loop's running total keeps the name and does the same job.

Why it fits here: It explains the name of this topic's running total: an accumulator gathers a result, round by round, as ENIAC's did.

Sources: Wikipedia: ENIAC; Penn Engineering: ENIAC

In one line

Most loops gather a result in an accumulator made before the loop: a total from 0, a count from 0, a largest from the first item, text from "". Each round changes it, and the result is read after the loop ends.

Loops as methods: forEach, map, filter, reduce

At a glance

A fruit seller sorting a crate does one job per pass: picks out the bruised ones, weighs the rest, then adds up the weights. Array methods give each such job a name.

The method forEach runs a callback for each item, map gives a new array of answers, and filter keeps the items that pass. The method reduce carries one result through, from a starting value, and some and every answer questions about the whole list. Chain them, and print between the steps when one goes wrong.

Take a guess: What does map give back, compared with forEach?

The patterns of the last section are so common that arrays carry them as methods. Each takes a callback, calls it for every item, and does one of the patterns for you. The functions lesson called such methods higher-order: you give the small job, and the method does the looping.

MethodWhat it does with your callbackWhat it gives back
forEach(f)calls f for each itemundefined
map(f)calls f for each item, and keeps each answera new array of the answers, the same length
filter(f)keeps each item for which f is truthya new array, often shorter
reduce(f, start)carries a running result through every itemthe final result
some(f)asks whether f is truthy for at least one itemtrue or false
every(f)asks whether f is truthy for every itemtrue or false

forEach: do something with each item

const nums = [1, 2, 3];
nums.forEach((n, i) => console.log(i, n * 10));
0 10
1 20
2 30

The callback receives each item and, as a second argument, its index. forEach gives back nothing, so it is for jobs with a side effect, such as printing. It cannot be stopped early with break; when a loop may need to stop, use for...of.

map: a new array of answers

const prices = [100, 250, 80];
const withGst = prices.map((p) => p * 118 / 100);
console.log(withGst, prices);
[ 118, 295, 94.4 ] [ 100, 250, 80 ]

map makes a new array of the same length, each item being the callback's answer for the item in the same place. The original prices are unchanged. Read it aloud as "prices, each mapped to its price with GST".

filter: keep only some items

const marks = [45, 80, 20, 95];
const passed = marks.filter((m) => m >= 33);
console.log(passed, marks.length, passed.length);
[ 45, 80, 95 ] 4 3

filter keeps the items for which the callback gives a truthy answer, in their order, in a new array. The callback is a test, as with find, but filter keeps every match, not only the first.

reduce: one result from many

const prices = [120, 45, 300];
const total = prices.reduce((sum, p) => sum + p, 0);
console.log(total);
465

reduce is the running total of the patterns section, as a method. Its callback receives the result so far, here named sum, and the next item, and returns the new result. The second argument of reduce, 0, is the starting value. Round by round: 0 + 120 is 120, 120 + 45 is 165, 165 + 300 is 465.

A common mistake

Leaving out reduce's starting value. On an empty array there is then nothing to start from, and reduce stops the program; with a starting value it gives that value back:

console.log([].reduce((a, b) => a + b, 0));
0
console.log([].reduce((a, b) => a + b));
Uncaught TypeError: Reduce of empty array with no initial value
    at line 1

some and every: questions about the whole list

const marks = [45, 80, 20, 95];
console.log(marks.some((m) => m < 33), marks.every((m) => m >= 33), [].every((m) => m > 100));
true false true

The method some asks "is at least one item like this?", and stops at the first yes. The method every asks "is every item like this?", and stops at the first no. On an empty array, every gives true, as no item breaks the rule; it is worth remembering when a list may be empty.

Chaining

map and filter give back arrays, so another method can be called straight on the answer. A chain reads left to right, like a recipe:

const total = [3, 4].map((n) => n * n).filter((n) => n > 10).reduce((a, b) => a + b, 0);
console.log(total);
16

Square each number: 9 and 16. Keep those over 10: 16. Add them up: 16.

A common mistake

Writing map's callback with braces and no return. As the functions lesson showed, an arrow with braces gives back undefined unless it returns, so every item of the new array is undefined:

const doubled = [1, 2, 3].map((n) => {
  n * 2;
});
console.log(doubled);
[ undefined, undefined, undefined ]

Worked example 6

A shop's items cost ₹120, ₹45, ₹300 and ₹80. Find the total of the items under ₹200, after adding 18% GST to each, with one chain.

What we have: four prices, a limit of 200 and a GST of 18%

What we need: one number: the total with GST of the cheaper items

The plan: filter the cheap items, map each to its price with GST, then reduce to a total

const prices = [120, 45, 300, 80];
const total = prices
  .filter((p) => p < 200)
  .map((p) => p * 118 / 100)
  .reduce((sum, p) => sum + p, 0);
console.log(total);
289.1
  1. filter keeps 120, 45 and 80. map gives 141.6, 53.1 and 94.4. reduce adds them.

The total is ₹289.10.

Check: (120 + 45 + 80) × 1.18 = 245 × 1.18 = 289.1.

A path that fails: putting map before filter with the same limit. The prices with GST are then tested against 200, and an item of ₹180 would become ₹212.40 and be left out, though its price was under 200.

When you are stuck: an array method gives undefined or the wrong array

forEach gives back undefined; use map when you want a new array.

If map gives undefined items, its callback has braces and no return.

Give reduce a starting value, such as 0, as its second argument.

In a chain, print the result after each step to find the step that went wrong.

Your turn

const words = ["tea", "chai", "kahwa"];
console.log(words.map((w) => w.length), words.filter((w) => w.length > 3));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 3, 4, 5 ] [ 'chai', 'kahwa' ]
  1. map gives each word's length.
  2. filter keeps the words longer than 3 letters.

It prints [ 3, 4, 5 ] [ 'chai', 'kahwa' ].

What do [2, 4, 6].every((n) => n % 2 === 0) and [2, 4, 7].some((n) => n % 2 === 1) give?Tap to reveal
  1. Every number in the first array is even: true.
  2. 7 in the second array is odd, so at least one is: true.

Both give true.

Use reduce to multiply all the numbers in [2, 3, 4].Tap to reveal
  1. The starting value for a product is 1, which changes nothing when multiplied.
console.log([2, 3, 4].reduce((product, n) => product * n, 1));
24

24: 1 × 2 × 3 × 4.

Did you know?

Map and reduce at Google's scale

The names map and reduce grew far beyond arrays. In 2004, Jeffrey Dean and Sanjay Ghemawat of Google described MapReduce, a programming model for processing and generating large data sets. They wrote that their abstraction was inspired by the map and reduce primitives present in Lisp and many other functional languages. The same two ideas sit in every JavaScript array.

Why it fits here: It shows how far this topic's methods reach: the same map and reduce that tidy one array also process data across many machines.

Sources: Google Research: MapReduce, Simplified Data Processing on Large Clusters; MapReduce paper (OSDI 2004)

The empty-list trap

The method reduce has one trap on empty lists. MDN lists a TypeError, thrown if the array contains no elements and no initial value is provided, and the standard's steps say the same. So [].reduce((a, b) => a + b) fails, while [].reduce((a, b) => a + b, 0) gives 0. A starting value makes the method safe.

Why it fits here: It is the reason this topic always passes reduce a starting value: with one, an empty list gives a sensible answer.

Sources: MDN: Array.prototype.reduce(); ECMAScript Language Specification: Array.prototype.reduce

In one line

forEach runs a callback for each item; map gives a new array of answers; filter keeps the items that pass; reduce carries one result through, from a starting value; some and every answer questions about the whole list. Chain them, and print between the steps when one goes wrong.

Where it is used

Wherever a program handles many things of one kind, a loop is at work. Here is where each idea of this lesson shows up in real work.

What you learnedWhere it is usedA real example
the for loopa known number of roundsprinting roll numbers 1 to 40 on a class register
whilerounds that depend on what happensa game that keeps going while the player has lives left
for...ofevery item of a listsending a reminder SMS to each student with fees due
breakstopping at the first matcha search that stops at the first free seat
continueskipping some itemsskipping cancelled orders when adding up a day's sales
nested loopsgrids and pairsthe rows and columns of a seating chart
accumulatorstotals, counts and recordsthe day's total sales, the number of late trains, the highest score
map and filterturning and choosing listsprices with tax added; only the products in stock
reduceone result from a listthe total of a cart
some and everyquestions about a whole listdoes any item need a cold chain? Has every student signed the form?

Mistakes and debugging

These are the slips that people meet most often with loops. Every output below is the real one, from the code shown.

1. One round too many

const prices = [120, 45, 300];
let total = 0;
for (let i = 0; i <= prices.length; i++) {
  total += prices[i];
}
console.log(total);
NaN

No error: the last round adds prices[3], which is undefined. The fix: i < prices.length.

2. One round too few

let lit = 0;
for (let lamp = 1; lamp < 40; lamp++) {
  lit++;
}
console.log(lit);
39

No error: numbers from 1 stop one short with <. The fix: lamp <= 40.

3. A loop that never ends

A loop whose condition never becomes false runs until the page stops it, after 3 seconds, with the message Stopped: the code ran for more than 3 seconds (an endless loop, or a timer that never stops). The fix: make sure the block moves the condition towards false, and prefer < or > to !== in the condition.

4. An accumulator made inside the loop

for (const p of [120, 45]) {
  let total = 0;
  total += p;
}
console.log(typeof total);
undefined

No error: total was made afresh in each round, and is gone after the loop. The fix: make it before the loop.

5. for...in on an array

let s = 0;
for (const i in [5, 6]) {
  s += i;
}
console.log(s);
001

No error: for...in gives the indexes as strings, and += joins them. The fix: for (const n of [5, 6]).

6. Expecting forEach to give back an array

const result = [1, 2, 3].forEach((n) => n * 2);
console.log(result);
undefined

No error: forEach always gives back undefined. The fix: map.

7. reduce with no starting value

console.log([].reduce((a, b) => a + b));
Uncaught TypeError: Reduce of empty array with no initial value
    at line 1

The fix: give the starting value as reduce's second argument: reduce((a, b) => a + b, 0).

The debugging corner: print each round

For any loop that misbehaves, print the counter and the accumulator at the top of each round: console.log(i, total);. The first line shows where the loop started, the last where it stopped, and the lines between show the round where the result went wrong. In the Sources panel of the DevTools step, a breakpoint inside the loop with a condition such as i === 39 stops only at the round you care about.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

// for: start; condition; step. From 0 with < length for an array
const prices = [120, 45, 300];
let total = 0;
for (let i = 0; i < prices.length; i++) {
  total += prices[i];
}
console.log(total);

// while: when the rounds cannot be counted; do...while runs at least once
let jar = 500;
while (jar < 1000) {
  jar += 200;
}
console.log(jar);

// for...of: every item; break stops, continue skips a round
for (const p of prices) {
  if (p < 100) continue;
  if (p > 200) break;
  console.log("checked", p);
}

// the methods: map, filter, reduce, some, every
console.log(prices.map((p) => p * 2), prices.filter((p) => p > 100), prices.reduce((s, p) => s + p, 0));
console.log(prices.some((p) => p > 200), prices.every((p) => p > 0));
465
1100
checked 120
[ 240, 90, 600 ] [ 120, 300 ] 465
true true
When you seeIt meansLook at
undefined or NaN after a loop over an arrayone round too many< with the length
the last item left outone round too few<= for numbers counted from 1
Stopped: the code ran for more than 3 secondsa loop that never endsthe step, and the condition
a total of 0, or a total that does not existan accumulator made inside the loopmake it before the loop
indexes as text, such as 001for...in on an arrayfor...of
undefined from forEachforEach gives nothing backmap
TypeError: Reduce of empty array with no initial valuereduce with nothing to start froma starting value

The story: Start, stop, step

You find the stopping question first. The loop kept going only while the lamp number was below forty, so lamp forty was never reached, and one character fixes it. In last week's copy, nothing moved the lamp number on at all, so the loop asked the same question about the same lamp until the oil ran out.

At dusk, forty lamps come on, from the Clock Tower to the ferry steps, and the clockwork stops at the last one.

Master Verge watches the road light up. "Start, stop, step," he says. "Next, it must remember more than one thing about each lamp."

Reagents gathered: for, while, for...of, break, map, filter.

Sources