Sub topic 8
Counting Loops with for
This chapter assumes you know let and const, can index into arrays, and have read the previous chapter on while loops. A for loop is a while loop with its setup, test, and update moved into one line. That layout makes it the usual choice when you know how many times to repeat, or when you walk through an array by index.
The Three Parts of the Header
The header has three parts separated by semicolons: for (initialization; condition; update).
for (let i = 0; i < 3; i++) {
console.log("pass", i);
}
// pass 0
// pass 1
// pass 2The parts run in a fixed order:
- The initialization (
let i = 0) runs once, before anything else. - The condition (
i < 3) is checked before every pass. If it is falsy, the loop ends. - The body runs.
- The update (
i++) runs after the body, and then control goes back to the condition.
Because the condition is tested first, a for loop whose condition starts out false never runs its body. The same is true of while.
Walking an Array by Index
The most common use is visiting each index of an array:
const prices = [4.5, 10, 2.25];
let total = 0;
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
console.log(total); // 16.75Use an index loop when you need the index itself. Examples include comparing neighbours, writing into a second array at the same position, or stepping by something other than 1. When you only need the values, for...of (covered in a later chapter) is shorter.
Counting Down and Stepping
The update can be any expression. You can count backwards or skip elements:
for (let i = 5; i > 0; i--) {
console.log(i); // 5, 4, 3, 2, 1
}
for (let i = 0; i <= 10; i += 5) {
console.log(i); // 0, 5, 10
}Counting backwards is useful when you remove items from an array as you go. Removing an element shifts the later elements down, but the indices you have not visited yet are all lower than the current one, so none get skipped.
Common Errors
| Mistake | Example | Result |
|---|---|---|
| Off-by-one with `<=` | `i <= arr.length` | Last pass reads `arr[arr.length]`, which is `undefined` |
| Update moves away from the condition | `for (let i = 0; i < 5; i--)` | Infinite loop |
| Removing items while counting up | `arr.splice(i, 1)` with `i++` | The element after each removed one is skipped |
| Comma instead of semicolon | `for (let i = 0, i < 3, i++)` | `SyntaxError` |
Optional Parts and Multiple Variables
Any of the three parts can be left empty, but the semicolons must stay. for (;;) is an infinite loop that has to be stopped from inside the body. You can also declare several variables and update them with the comma operator:
const word = "level";
let isPalindrome = true;
for (let left = 0, right = word.length - 1; left < right; left++, right--) {
if (word[left] !== word[right]) {
isPalindrome = false;
}
}
console.log(isPalindrome); // trueDeclare the counter with let so that it exists only inside the loop. The chapter on scope and closures explains why var behaves differently here.
Exercise
What does this code log, and why? const a = [1, 2, 3]; let s = 0; for (let i = 0; i <= a.length; i++) { s += a[i]; } console.log(s);
Show answer
It logs NaN. The condition i <= a.length allows a fourth pass with i = 3, and a[3] is undefined. Adding undefined to a number gives NaN. Changing the condition to i < a.length makes it log 6.
Exercise
Write a for loop that logs every second element of const xs = ["a", "b", "c", "d", "e"], starting with "a".
Show answer
for (let i = 0; i < xs.length; i += 2) { console.log(xs[i]); } logs "a", "c", "e".