Loops & Iteration
Published by Brayan K
Computers are brilliant at doing the same thing thousands of times without complaint. Loops are how you tell them to — rendering a list of products, summing a cart, retrying a request, or scanning a file line by line.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Trace the check before counting the passes
A loop repeats its body according to a rule. For a for loop, read four stages: initialise once, test the condition, run the body if the test passes, then update before testing again. The condition describes when to continue, not when to stop.
for (let index = 0; index < 3; index += 1) {
console.log("index", index);
}
console.log("finished");
// ✅ Expected output:
// index 0
// index 1
// index 2
// finishedThe first body uses the initial counter. After each completed body, the update advances it. When the condition is false, execution moves to the statement after the loop. Printing inside the body gives one message per pass; printing after the closing brace happens once.
let exclusive = 0;
for (let index = 0; index < 3; index += 1) {
exclusive += 1;
}
let inclusive = 0;
for (let index = 0; index <= 3; index += 1) {
inclusive += 1;
}
console.log(exclusive);
console.log(inclusive);
// ✅ Expected output:
// 3
// 4Changing < to <= includes the boundary value. Before running a loop, write down its first value, last included value and value that makes the condition false. That catches an extra pass more reliably than guessing a count from the number in the condition.
let visits = 0;
for (let index = 5; index < 5; index += 1) {
visits += 1;
}
console.log(visits);
// ✅ Expected output:
// 0Keep the accumulated result outside the repeated body
An accumulator keeps work from earlier passes. Declare it before the loop, then update it inside. Declaring it inside the body starts a new value on every pass, so it cannot hold the running total you intended.
for (let value = 1; value <= 3; value += 1) {
let total = 0;
total += value;
console.log(total);
}
// ✅ Expected output:
// 1
// 2
// 3let total = 0;
for (let value = 1; value <= 3; value += 1) {
total += value;
console.log("running", total);
}
console.log("final", total);
// ✅ Expected output:
// running 1
// running 3
// running 6
// final 6The counter declared with let in a loop header belongs to that loop. It is not an output variable you can read afterwards. Keep a separate result outside when later code needs one; Scope & var/let/const (TDZ) owns the wider rules for binding visibility.
for (let index = 0; index < 2; index += 1) {
console.log(index);
}
console.log(index);
// ✅ Expected output:
// 0
// 1
// ✅ Expected error:
// ReferenceError: index is not definedA while loop needs progress towards a false condition
Use while when the continuation test is clearer than a counting header. The test still happens before the body. Identify which statement changes the value used by that test; if nothing can change it, a true condition can stay true forever.
let remaining = 3;
while (remaining > 0) {
console.log("remaining", remaining);
remaining -= 1;
}
console.log("after", remaining);
// ✅ Expected output:
// remaining 3
// remaining 2
// remaining 1
// after 0Removing the decrement would remove progress. Instead of running that unbounded mistake in the browser, this short diagnostic checks the unchanged condition a fixed number of times. The repeated true result explains why the original loop would not finish.
const remaining = 3;
for (let check = 0; check < 3; check += 1) {
console.log(remaining > 0, remaining);
}
// ✅ Expected output:
// true 3
// true 3
// true 3Trace suspected nonterminating loops before running them. In this editor, Console mode keeps the page responsive so Stop can interrupt a loop. Web page mode provides page APIs, and a synchronous loop there can keep the controls busy. A small explicit iteration bound helps you inspect what changes on each pass.
Decide whether one pass is required
while checks first, so it can run zero times. do...while runs the body first and checks afterwards, so it runs at least once. Choose the latter only when the initial action is required even if the continuation condition is already false.
let before = 0;
while (false) {
before += 1;
}
let after = 0;
do {
after += 1;
} while (false);
console.log(before);
console.log(after);
// ✅ Expected output:
// 0
// 1The trailing semicolon is part of the do...while statement. This distinction matters for retry-like actions: “try once, then decide whether to repeat” is different from “check eligibility before trying.” Network retry policy itself belongs to Advanced Fetch API Patterns (Retry, Timeout, AbortController).
Choose values, positions or property names deliberately
The examples below use an array literal: an ordered list written between square brackets. An array’s first position is zero. Arrays and Objects owns creating and changing collections; here the question is what the loop variable receives.
const quantities = [2, 5, 3];
let total = 0;
for (const quantity of quantities) {
total += quantity;
}
console.log(total);
// ✅ Expected output:
// 10for...of supplies successive values from an iterable. A new loop binding is used for each pass, so const is appropriate when the body does not reassign that pass’s variable. Use a counter loop when the numeric position itself is needed.
const labels = ["tea", "coffee"];
for (let index = 0; index < labels.length; index += 1) {
console.log(index, labels[index]);
}
// ✅ Expected output:
// 0 tea
// 1 coffeeconst labels = ["tea", "coffee"];
labels.note = "packed";
for (const key in labels) {
console.log(typeof key, key);
}
// ✅ Expected output:
// string 0
// string 1
// string notefor...in enumerates enumerable string property names, including inherited ones; it is not an array-values loop. The extra named property is visited here too. Even an array index arrives as text through this operation, so adding a number to it can join strings. Use for...of for ordinary value iteration.
const record = { tea: 2, coffee: 1 };
for (const value of record) {
console.log(value);
}
// ✅ Expected error:
// TypeError: record is not iterableBeing an object is not the same as being iterable. For a record’s own enumerable values, choose an explicit operation such as Object.values; Iterators & Iterables owns the protocol behind for...of.
Skip one pass or leave the nearest loop
continue skips the rest of the current body. break leaves the nearest enclosing loop in these unlabelled examples. The small if guards below choose when to do that; Conditionals & Operators owns constructing those decisions.
for (let value = 1; value <= 4; value += 1) {
if (value === 2) continue;
console.log(value);
}
// ✅ Expected output:
// 1
// 3
// 4A for loop performs its update after continue. A while loop goes back to its condition; it has no automatic update. Put any necessary progress before a branch that could skip it.
let value = 0;
while (value < 4) {
value += 1;
if (value === 2) continue;
console.log(value);
}
// ✅ Expected output:
// 1
// 3
// 4for (let row = 1; row <= 2; row += 1) {
for (let column = 1; column <= 3; column += 1) {
if (column === 2) break;
console.log(row, column);
}
}
console.log("done");
// ✅ Expected output:
// 1 1
// 2 1
// doneThe inner loop stops at its guard, but the outer loop still advances to its next row. Do not read an unlabelled break as “exit every loop” or “return from the function.” A function’s return is a different control-flow operation.
Complete a running count and total
Fill the two blanks so the loop visits the integers from one through four, adds each to a running total, and prints that final total once. Each hint supplies the exact replacement. Keep the accumulator outside the loop.
let total = 0;
for (let value = 1; ___; value += 1) {
// 👉 replace ___ with value <= 4
total += ___;
// 👉 replace ___ with value
}
console.log(total);
// ✅ Expected output:
// 10After it works, change the boundary to exclude four and predict how the final total changes. Do not move the total’s declaration into the body; that would change the lifetime of the accumulated result.
Count and total only accepted quantities
Given [3, -1, 0, 5], write a loop that ignores quantities less than or equal to zero. Maintain an accepted-item count and a total outside the loop. Print the accepted count and then the total on separate lines. Use continue for rejected values so the accepted work is easy to follow.
const quantities = [3, -1, 0, 5];
let accepted = 0;
let total = 0;
for (const quantity of quantities) {
if (quantity <= 0) continue;
accepted += 1;
total += quantity;
}
console.log(accepted);
console.log(total);
// ✅ Expected output:
// 2
// 8Try an empty array and then an array containing only rejected values. The initial zero values are still meaningful results when the loop accepts nothing. That is another reason to initialise the result before iteration.
Reference: MDN’s loops and iteration guide.
Practice quiz
What does this complete program print? let count = 0; for (let i = 0; i < 3; i += 1) count += 1; console.log(count);
- 3
- 2
- 4
- 0
Answer: 3. The included counter values are zero, one and two.
What does this complete program print? let count = 0; for (let i = 0; i <= 3; i += 1) count += 1; console.log(count);
- 3
- 4
- 2
- 0
Answer: 4. The inclusive condition also admits the boundary value three.
What does this complete program print? for (let value = 1; value <= 3; value += 1) { let total = 0; total += value; console.log(total); }
- 1 3 6
- 6
- 1 2 3
- 0 0 0
Answer: 1 2 3. The total is reinitialised inside each pass, so it does not accumulate earlier values.
What does this complete program print? let count = 0; do { count += 1; } while (false); console.log(count);
- 0
- 2
- The body never executes
- 1
Answer: 1. A do...while body runs before its first condition check.
What does this complete program print? for (let i = 1; i <= 3; i += 1) { if (i === 2) continue; console.log(i); }
- 1 3
- 1 2 3
- 1
- 3
Answer: 1 3. Continue skips the print for the second pass, then the for-loop update advances the counter.
What does this complete program print? const values = [4, 6]; for (const key in values) console.log(key + 1);
- 1 2
- 01 11
- 5 7
- 0 1
Answer: 01 11. for...in supplies string property names, so adding one joins text.
What does this complete program print? let count = 0; for (let row = 0; row < 2; row += 1) { for (let column = 0; column < 3; column += 1) { if (column === 1) break; count += 1; } } console.log(count);
- 1
- 3
- 2
- 6
Answer: 2. Each outer pass admits one inner increment before the inner break.
What does this complete program print? const values = []; let total = 0; for (const value of values) total += value; console.log(total);
- undefined
- NaN
- ReferenceError
- 0
Answer: 0. The empty iterable makes no passes, and the accumulator keeps its initial value.
Continue this course
- Previous: Numbers & Math
- Next: Conditionals & Operators — if/else, switch, ternary, &&/||, plus ?? and ?. (optional chaining)
- Quick reference: JavaScript cheat sheet