Repeat Code With a Counter
JavaScript for Loops
The classic `for` loop runs code while a counter is in range. Three parts: init, condition, step.
What you'll learn
- Write a `for` loop with init, condition, step
- Iterate a fixed number of times
- Use `let` for the loop variable
A for loop runs a block of code repeatedly while a condition holds.
The classic form has three parts inside the parentheses:
for (init; condition; step) {
// body
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
// 0
// 1
// 2
// 3
// 4 What happens:
- Init:
let i = 0runs once before the loop. - Condition:
i < 5is checked. If true, run the body. - Body:
console.log(i). - Step:
i++runs after each iteration. - Repeat from step 2.
Walking Through an Array
const fruits = ["apple", "banana", "grape"];
for (let i = 0; i < fruits.length; i++) {
console.log(`${i}: ${fruits[i]}`);
}
// "0: apple"
// "1: banana"
// "2: grape" This works but is verbose. For “do something with each item”,
for..of (next lesson) reads better. Use the indexed for when you
need the index, or when you’re iterating numerically.
Counting Down
for (let i = 10; i > 0; i--) {
console.log(i);
}
console.log("Liftoff!"); Skipping Values
for (let i = 0; i <= 10; i += 2) {
console.log(i);
}
// 0, 2, 4, 6, 8, 10 Always Use let for the Counter
let i = 0 gives the counter block scope — each loop iteration
effectively gets its own i. This avoids a class of bugs that
plagued JavaScript before ES6.
Infinite Loops
If your condition never becomes false, you’ve got an infinite loop — the browser will hang.
// Will run forever:
// for (let i = 0; i < 10; i--) { … }
// ← oops, i goes DOWN, never reaches 10
// Will run forever:
// for (let i = 0; ; i++) { … }
// ← no condition If your editor or browser tab freezes, this is the usual suspect.
Up Next
For iterating arrays and other collections, for..of is the modern
idiom.