Sub topic 8
Counting Loops with for
This chapter assumes you can read and write while loops, compare numbers with <, <=, and ===, and index into arrays with arr[i]. The classic for loop packs the three parts of a counting loop into one line: where the counter starts, when the loop stops, and how the counter changes. Because all three sit together, you can see the loop's whole range at a glance. That makes for the usual choice when you need an index, a fixed number of repetitions, or an unusual step.
Anatomy of a for Loop
A for statement has a header with three clauses separated by semicolons, followed by a body:
for (let i = 0; i < 3; i++) {
console.log("iteration", i);
}
// iteration 0
// iteration 1
// iteration 2| Clause | Example | When it runs |
|---|---|---|
| Initialization | `let i = 0` | Once, before anything else |
| Condition | `i < 3` | Before every iteration, including the first |
| Update (final expression) | `i++` | After every iteration's body |
The condition is checked before the first iteration. If it is false from the start, the body never runs. This matches a while loop and differs from do...while.
Execution order
The engine always follows the same cycle: initialize once, then test, run the body, update, and test again.
The counter therefore holds one more update than the body ever saw. When the loop above exits, i is 3. If you declared it with let, i is out of scope after the loop. The chapter on let vs var covers how that scoping works.
The equivalent while loop
Any for loop can be rewritten as a while loop. Seeing the rewrite makes the order explicit:
{
let i = 0; // initialization
while (i < 3) { // condition
console.log("iteration", i);
i++; // update
}
}The two forms are not perfectly identical. A continue inside the for body still runs the update, but a continue inside this while body would skip i++ and loop forever. Also, let in a for header creates a fresh binding on every iteration, which matters when closures capture the counter. Later chapters cover both differences.
Counting Patterns
Up, down, and by steps
You can change the start value, the comparison, and the update to get any arithmetic sequence:
// Count up: 0 1 2 3 4
for (let i = 0; i < 5; i++) console.log(i);
// Count down: 3 2 1
for (let i = 3; i > 0; i--) console.log(i);
// Step by 5, inclusive end: 0 5 10 15 20
for (let i = 0; i <= 20; i += 5) console.log(i);
// Powers of two below 100: 1 2 4 8 16 32 64
for (let i = 1; i < 100; i *= 2) console.log(i);The update can be any expression, not just ++ or --. The loop ends when the condition becomes false, so your condition must eventually fail given your update. A loop that counts down while testing i < 10 never ends.
Iterating an array by index
The most common use of for is walking an array when you need the position as well as the value:
const scores = [72, 95, 88];
for (let i = 0; i < scores.length; i++) {
console.log(`#${i + 1}: ${scores[i]}`);
}
// #1: 72
// #2: 95
// #3: 88Indexes start at 0 and the last valid index is length - 1. That is why the idiomatic condition is i < arr.length, not i <= arr.length.
If you only need values, for...of (next chapters) is clearer. Use the indexed for when you need the index itself, need to look at neighboring elements (arr[i - 1], arr[i + 1]), skip by more than one, go backward, or modify the array while you walk it.
Comparing neighbors
Index access lets you compare each element with the one before it, which for...of cannot do directly:
const temps = [12, 15, 14, 18, 18, 21];
let rises = 0;
for (let i = 1; i < temps.length; i++) {
if (temps[i] > temps[i - 1]) rises++;
}
console.log(rises); // 3Starting at i = 1 guarantees temps[i - 1] always exists.
Off-by-One Errors
Off-by-one errors are the classic for bug: the loop runs one time too many or too few. They come from mixing up inclusive and exclusive bounds.
const items = ["a", "b", "c"];
for (let i = 0; i <= items.length; i++) {
console.log(items[i]);
}
// a
// b
// c
// undefined <- i === 3 is past the endJavaScript does not throw when you read past the end of an array. It quietly returns undefined, so this bug often shows up later as NaN or "undefined" in output rather than as an error.
A simple rule prevents most of these bugs. Use a half-open range: start inclusive, end exclusive (i = start; i < end). The loop then runs exactly end - start times, and an empty range (start === end) runs zero times without any special case.
Edge Cases and Gotchas
Changing the array while looping
The condition i < arr.length is re-evaluated every iteration, so it sees the array's current length. That helps when you append items, but removing items while counting forward skips elements:
const forward = [1, 2, 2, 3];
for (let i = 0; i < forward.length; i++) {
if (forward[i] % 2 === 0) forward.splice(i, 1);
}
console.log(forward); // [1, 2, 3] <- one 2 was skipped
const backward = [1, 2, 2, 3];
for (let i = backward.length - 1; i >= 0; i--) {
if (backward[i] % 2 === 0) backward.splice(i, 1);
}
console.log(backward); // [1, 3]When splice removes index 1, the second 2 shifts into index 1, and then i++ moves past it. Counting backward avoids this because removing an element only shifts elements you have already visited. If you don't need to mutate in place, building a new array with filter is simpler, as the array methods chapter shows.
Caching the length
You will sometimes see for (let i = 0, len = arr.length; i < len; i++). Modern engines make reading .length cheap, so caching rarely improves speed. It does change behavior: the loop ignores items added during iteration, and if items are removed it reads past the new end. Cache the length only when you want that fixed bound.
Multiple counters with the comma operator
The initialization can declare several variables, and the update can use the comma operator to change several at once. The two-pointer pattern relies on this:
const chars = ["r", "a", "c", "e", "s"];
for (let left = 0, right = chars.length - 1; left < right; left++, right--) {
const tmp = chars[left];
chars[left] = chars[right];
chars[right] = tmp;
}
console.log(chars.join("")); // "secar"const in the header
const works in for...of, but not with a counter you update:
try {
for (const i = 0; i < 3; i++) {
console.log(i); // prints 0 once
}
} catch (err) {
console.log(err.name); // "TypeError"
}The body runs once, then i++ tries to reassign a constant and throws. Use let for counters.
Omitted clauses
All three clauses are optional, but the semicolons are required. for (;;) is an infinite loop that you must leave with break or return:
let n = 27;
let steps = 0;
for (;;) {
if (n === 1) break;
n = n % 2 === 0 ? n / 2 : 3 * n + 1;
steps++;
}
console.log(steps); // 111When there is no counter, a while loop usually reads better. Reserve for (;;) for code where the exit condition truly belongs in the middle of the body.
Floating-point counters
Avoid fractional counters. Decimal steps accumulate rounding error:
let count = 0;
for (let x = 0; x < 1; x += 0.1) count++;
console.log(count); // 11, not 10
// Count with integers, derive the fraction
for (let i = 0; i < 10; i++) {
const x = i / 10;
// x is 0, 0.1, ..., 0.9
}After ten additions x is 0.9999999999999999, which is still less than 1, so the loop runs an eleventh time. With a condition like x !== 1 the loop would never end.
Common Errors at a Glance
| Symptom | Likely cause | Fix |
|---|---|---|
| Last value is `undefined` | `i <= arr.length` | Use `i < arr.length` |
| First element missing | Started at `i = 1` by accident | Start at `0` unless you compare neighbors |
| Loop never ends | Update moves away from the condition, or float step | Check direction; count with integers |
| Elements skipped | Removing items while counting forward | Count backward or use `filter` |
| `TypeError: Assignment to constant variable` | `const` counter | Use `let` |
| Body never runs | Condition false at start (e.g. `i > 0` with `i = 0`) | Check initial value against condition |
Exercise
What does this code log, and why? for (let i = 10; i > 0; i -= 3) console.log(i);
Show answer
It logs 10, 7, 4, 1. After printing 1, the update sets i to -2, the condition -2 > 0 is false, and the loop exits. The loop never prints 0 or a negative number because the condition is checked before each body run.
Exercise
Write a for loop that sums every other element of const data = [4, 8, 15, 16, 23, 42]; starting at index 0, and say what the sum is.
Show answer
let sum = 0; for (let i = 0; i < data.length; i += 2) { sum += data[i]; } visits indexes 0, 2, and 4 (values 4, 15, 23), so sum is 42. Using i < data.length keeps the loop safe for odd-length arrays too.
Exercise
A teammate removes empty strings from an array in place with for (let i = 0; i < arr.length; i++) { if (arr[i] === "") arr.splice(i, 1); }. With ["a", "", "", "b"] the result is ["a", "", "b"]. Explain the bug and give two fixes.
Show answer
Removing index 1 shifts the second empty string into index 1, and then i++ moves on to index 2, skipping it. Fix 1: loop backward, for (let i = arr.length - 1; i >= 0; i--), so shifts only affect elements you have already checked. Fix 2: skip the mutation and build a new array with arr.filter((s) => s !== "").