for Loop: Counter-Driven IterationThe JavaScript for loop repeats a block of code a known number of times using a loop counter. It combines initialization, a continuation test, and a step update on one compact line.
for Loop HeaderA classic for loop has three semicolon-separated expressions inside for (init; condition; step):
let i = 0): Runs once before the loop begins. Always declare i with let, never var.i < limit): Checked before every iteration; the loop stops as soon as it becomes falsy.i++): Runs at the end of each iteration body before the next condition check.for Loop ExampleClassic for loops shine when you need exact numeric ranges, step sizes other than 1, or backward iteration. When simply reading every item in an array, for...of is usually cleaner.
// Count down in steps of 2
for (let count = 6; count >= 0; count -= 2) {
console.log("Countdown:", count);
}
// Compute running total with index access
const dailySales = [120, 150, 90, 210];
let total = 0;
for (let i = 0; i < dailySales.length; i++) {
total += dailySales[i];
console.log(`Day ${i + 1} cumulative: $${total}`);
}
<= arr.length instead of < arr.length: Because array indexes stop at length - 1, <= reads arr[length] on the final pass and yields undefined.i-- when checking i < 10, or forgetting to update i, freezes the browser tab forever.const i = 0 in a standard for header: Because i++ reassigns i, using const throws a TypeError on the first update. Use let.for (;;) header?Yes, any of the three parts is optional, though if you omit the condition you must break inside the body to prevent an infinite loop.
let instead of var in a for loop?let creates a fresh variable per iteration, preventing asynchronous callbacks inside the loop from reading the final overwritten counter value.
for over forEach()?Choose for (or for...of) when you need break, continue, await, or reverse iteration.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.