JS Loop For
JavaScript for Loop: Counter-Driven Iteration
The 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.
Anatomy of the for Loop Header
A classic for loop has three semicolon-separated expressions inside for (init; condition; step):
- Initialization (
let i = 0): Runs once before the loop begins. Always declareiwithlet, nevervar. - Condition (
i < limit): Checked before every iteration; the loop stops as soon as it becomes falsy. - Step (
i++): Runs at the end of each iteration body before the next condition check.
Practical for Loop Example
Classic 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}`);
}
Common Mistakes to Avoid
- Writing
<= arr.lengthinstead of< arr.length: Because array indexes stop atlength - 1,<=readsarr[length]on the final pass and yieldsundefined. - Creating an infinite loop: Writing
i--when checkingi < 10, or forgetting to updatei, freezes the browser tab forever. - Declaring
const i = 0in a standardforheader: Becausei++reassignsi, usingconstthrows aTypeErroron the first update. Uselet.
Frequently Asked Questions
Can I omit parts of the 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.
Why should I use 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.
When should I choose for over forEach()?
Choose for (or for...of) when you need break, continue, await, or reverse iteration.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.