After this lesson you can make JavaScript do something many times without copying and pasting lines: print the numbers 1 to 10, add up a list of prices, or visit every letter of a word. You should be comfortable with variables and operators, in particular i++ from Operators.
Why loops exist
Imagine printing the numbers 1 to 100. You could write 100 log calls, but a loop lets you write the instruction once and say "repeat". The most common loop is for.
The anatomy of a for loop
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
for (let i = 1; i <= 5; i++) {
log("Round", i);
}
</script>This prints Round 1 to Round 5, one per line. The header has three parts, separated by semicolons:
- Setup (
let i = 1) runs once, before the loop starts. It creates the counter. - Condition (
i <= 5) is checked before every pass. While it is true the body runs; when it is false the loop ends. - Update (
i++) runs after every pass, and adds one to the counter.
The order of events is: setup, then check, body, update, check, body, update, and so on until the check fails. Walk through the example by hand once: i is 1, the check passes, Round 1 is logged, i becomes 2... and when i becomes 6 the check 6 <= 5 fails and JavaScript moves on to the code after the loop.
Declare the counter with let, not const, because it changes. The name i is a convention for "index" and is fine for short loops. For nested loops people use j and k, or better, descriptive names like row and column.
Looping through an array
Arrays count from 0, so the first item is at index 0 and the last is at length - 1. That decides how the loop is written:
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
log(i, fruits[i]);
}
</script>The output is 0 apple, 1 banana and 2 cherry. Use < with length, never <=. With <=, the last pass would ask for fruits[3], which does not exist and gives undefined. Arrays get a full treatment in the Arrays lesson later; here you only need to know that fruits[i] reads one item.
for...of: when you do not need the index
If you just want each item, for...of is shorter and cannot go wrong with the bounds:
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
log(fruit.toUpperCase());
}
for (const letter of "cat") {
log(letter);
}
</script>This prints APPLE, BANANA, CHERRY, then c, a, t. A new const is created on every pass, so const works here. Note that for...of is for arrays, strings and similar collections. It does not work directly on a plain object like { a: 1 }, which has its own lesson later in the course.
If you need both the item and its position, use fruits.entries() with destructuring, or fall back to the classic for loop.
Variations: down, by steps, and nested
The three parts are ordinary code, so you can change them freely.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
// Counting down
const down = [];
for (let i = 3; i >= 1; i--) down.push(i);
log("down:", down);
// Steps of 2
const evens = [];
for (let i = 0; i <= 10; i += 2) evens.push(i);
log("evens:", evens);
// A loop inside a loop
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= 3; col++) {
line += row * col + " ";
}
log(line);
}
</script>The output is:
down: 3,2,1
evens: 0,2,4,6,8,10
1 2 3
2 4 6
3 6 9 (log joins values with a space, and an array turns into comma-separated text, which is why you see 3,2,1.) The inner loop runs completely for every pass of the outer loop. So three outer passes times three inner passes make nine multiplications. Nested loops are the way to handle grids, tables and combinations, but the work multiplies quickly, so avoid them for large data when you can.
Why let and not var
With let, each pass of the loop gets its own copy of i. That matters as soon as you create functions inside the loop that remember i later. The older var shares one variable across the whole loop, and a famous bug follows. The Variables lesson explains the difference, and you should simply use let in loop headers.
Common mistakes
- Off-by-one errors. Starting at 1 on an array skips the first item, and
i <= arr.lengthreads past the end. Test the first and last values. - Loops that never end. If the update goes the wrong way (
i--withi < 5) or is missing, the condition never becomes false, and the browser tab can freeze. Reload the page to recover. - A semicolon after the header.
for (...);gives the loop an empty body, and your block runs once afterwards. - Changing the array while looping over it. Adding or removing items inside a loop over the same array shifts indexes and skips or repeats items. Loop over a copy, or build a new array.
- Using
constfor the counter in a classic for loop.for (const i = 0; i < 3; i++)fails on the first update with a TypeError, because a constant cannot be changed. - Forgetting that
for...inis a different loop. It visits keys (and for arrays gives indexes as strings). For array items usefor...of.
Exercise
- Print the numbers 10 down to 1, then the word
Liftoff!. - Given
const prices = [120, 80, 45], use aforloop to log each price and a runningtotalvariable that you update inside the loop. After the loop, logTotal: 245. - Use nested loops to print a 4 by 4 multiplication table, one row per line.
- Challenge: print only the odd numbers from 1 to 15 in two different ways, using a step of 2 and using an
ifinside the loop.
Next: while and do...while loops, for repeating when you do not know the count in advance.
Key points
- A for loop has three parts in its header, setup, condition and update, followed by a block that runs on each pass.
- Use let for the counter so each pass has its own copy, and start counting at 0 for arrays.
- for...of gives you each item of an array or string directly, and is the simplest choice when you do not need the index.
- Counting down, stepping by 2 and nesting loops are all small variations on the same pattern.
- Most loop bugs are off-by-one errors, so check the first and last values the loop produces.