Lesson

JS Loop For

10 min reading
Free Course

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):

  1. Initialization (let i = 0): Runs once before the loop begins. Always declare i with let, never var.
  2. Condition (i < limit): Checked before every iteration; the loop stops as soon as it becomes falsy.
  3. 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.length instead of < arr.length: Because array indexes stop at length - 1, <= reads arr[length] on the final pass and yields undefined.
  • Creating an infinite loop: Writing i-- when checking i < 10, or forgetting to update i, freezes the browser tab forever.
  • Declaring const i = 0 in a standard for header: Because i++ reassigns i, using const throws a TypeError on the first update. Use let.

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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum