For Loops
A loop repeats a block of code. The for loop is used when you know, or can calculate, how many times to repeat: once for each grade from 9 to 12, once for each payment in a list, once for each month of the year. It keeps a counter variable, checks a condition before each round, and updates the counter after each round, all in one line.
In One Minute
for (let i = 0; i < n; i++) { ... }runs the bodyntimes, withigoing from0ton - 1.- The three parts: initialization (runs once), condition (checked before each round), update (runs after each round).
- Loop over an array by index with
i < list.length. For plain "each item" loops,for...of(later in this chapter) is simpler. - Declare the counter with
let, nevervar: each round then gets its own copy ofi.
The for Loop
Syntax
for (initialization; condition; update) {
// body: runs while condition is truthy
}| Part | Runs | Typical code |
|---|---|---|
| Initialization | Once, before the first round | let i = 0 |
| Condition | Before every round; the loop stops when it is falsy | i < 5 |
| Body | Once per round | your code |
| Update | After every round | i++ |
Example
for (let grade = 9; grade <= 12; grade++) {
console.log(`Grade ${grade}`);
}
console.log("Done");Grade 9
Grade 10
Grade 11
Grade 12
DoneExplanation: grade starts at 9. Before each round, JavaScript checks grade <= 12; if true, it runs the body, then grade++. When grade becomes 13, the condition is false, the loop ends, and the program continues with "Done".
Counting in Other Steps
The update can be any expression. Count down, or count in steps:
for (let i = 3; i >= 1; i--) {
console.log(`Reminder ${i}`);
}
let months = "";
for (let month = 1; month <= 12; month += 3) {
months += month + " ";
}
console.log("Quarter starts:", months);Reminder 3
Reminder 2
Reminder 1
Quarter starts: 1 4 7 10Looping Through an Array
Arrays are indexed from 0 to length - 1, which matches the i < length pattern exactly:
const fees = [120, 85, 45, 200];
let total = 0;
for (let i = 0; i < fees.length; i++) {
console.log(`Fee ${i + 1}: $${fees[i]}`);
total += fees[i];
}
console.log(`Total: $${total}`);Fee 1: $120
Fee 2: $85
Fee 3: $45
Fee 4: $200
Total: $450Use an index-based for when you need the index, need to skip or step through items, or need to loop backwards. When you only need each item, for...of is shorter, and array methods such as map and filter (in the arrays chapter) are often better still.
Nested Loops
A loop inside a loop runs the inner loop completely for each round of the outer one. Nested loops build tables:
const students = ["Navika", "Srihitha"];
const terms = ["Fall", "Spring"];
for (let s = 0; s < students.length; s++) {
for (let t = 0; t < terms.length; t++) {
console.log(`${students[s]} - ${terms[t]}`);
}
}Navika - Fall
Navika - Spring
Srihitha - Fall
Srihitha - SpringThe body runs 2 × 2 = 4 times.
In Practice
The Fee Tracker prints a fee table for grades 9 to 12. Fees rise $15 per grade from a base of $400:
const BASE = 400;
const STEP = 15;
console.log("Grade | Term fee");
for (let grade = 9; grade <= 12; grade++) {
const fee = BASE + (grade - 9) * STEP;
console.log(`${String(grade).padStart(5)} | $${fee}`);
}Grade | Term fee
9 | $400
10 | $415
11 | $430
12 | $445padStart(5) adds spaces on the left so the numbers line up under "Grade"; the string methods lesson explains it.
Common Mistakes
Off by one. i <= list.length reads past the end. Use i < list.length.
Changing the counter inside the body. i++ in both the update and the body skips items. Change the counter in one place.
An update that never reaches the end. for (let i = 0; i < 10; i--) counts the wrong way and never stops. Make sure the update moves toward the condition becoming false.
Using var for the counter. It leaks out of the loop and is shared between rounds. Use let.
Under the Hood
Before 2015, loop counters were declared with var. A var has one variable for the whole function, shared by every round. That causes a famous bug when the loop schedules work for later:
for (let i = 1; i <= 3; i++) {
setTimeout(() => console.log("let:", i), 0);
}for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log("var:", i), 0);
}
// prints "var: 4" three timeslet: 1
let: 2
let: 3Explanation: the timers run after the loop has finished. With var, all three functions look at the same i, which is 4 by then. With let, the specification creates a fresh binding of i for every round and copies the current value into it, so each function remembers its own i. This per-round copy is why let in a for loop "just works", and it is the first example of a closure, which has a lesson of its own later.
Interview Corner
Why does a for loop with var and setTimeout print the same number every time?
var is function-scoped, so all callbacks close over one shared i, which holds its final value when the timers run. let creates a new binding per iteration (the specification copies the value into a fresh environment each round), so each callback sees its own value. The pre-2015 fix was an IIFE that captured i as a parameter.
When would you use a classic for loop instead of for...of or array methods?
When you need the index, a step other than 1, reverse order, early exit with break on an index condition, or to mutate the array by index while looping. For plain iteration, for...of; for transformations, map, filter and reduce.
Practice
Challenge: Print the multiplication table for 5 from 5 x 1 = 5 to 5 x 5 = 25, then print the sum of all five results.
Show solution
let sum = 0;
for (let i = 1; i <= 5; i++) {
const result = 5 * i;
console.log(`5 x ${i} = ${result}`);
sum += result;
}
console.log("Sum:", sum);5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
Sum: 75Key Takeaways
| Loop | Pattern |
|---|---|
| Count up | for (let i = 0; i < n; i++) |
| Count down | for (let i = n - 1; i >= 0; i--) |
| Step by 3 | for (let i = 0; i < n; i += 3) |
| Array by index | for (let i = 0; i < arr.length; i++) |
Was this tutorial helpful?