References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript for statement

Statement JavaScript All modern browsers Updated
Quick answer

The for loop repeats code a set number of times using a counter. for (let i = 0; i < 5; i++) { ... } runs the block five times. Its three parts are the start, the condition to keep going, and the step. For looping over arrays, for...of or forEach() is usually cleaner.

Overview

The classic for loop runs a block repeatedly, with a counter you control. Its head has three semicolon-separated parts: the initializer (let i = 0), the condition checked before each pass (i < 5), and the step after each pass (i++). When the condition becomes false, the loop ends.

Use let (not var) for the counter so each iteration gets its own scoped i — this matters the moment a closure or callback inside the loop captures it. Inside the body, break exits the loop early and continue skips to the next iteration, giving you fine control.

That said, you often don't need a manual counter. To walk an array's values, for...of reads better; to transform or process each element, forEach(), map() and friends are clearer still. Reach for the plain for when you genuinely need the index, a non-unit step, or to stop partway with break.

Syntax

for (initializer; condition; step) {
  // body runs while condition is true
}

for (let i = 0; i < 5; i++) {
  console.log(i);  // 0, 1, 2, 3, 4
}

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  let sum = 0;
  const lines = [];

  for (let i = 1; i <= 5; i++) {
    sum += i;
    lines.push('i=' + i + ', sum=' + sum);
  }

  document.getElementById('out').textContent = lines.join('\n');
</script>

Best practices

  • Declare the counter with let so each iteration is correctly scoped, especially around closures.
  • Use break to exit early and continue to skip an iteration.
  • Prefer for...of or forEach() when you don't actually need the index.
  • Avoid recomputing things like arr.length needlessly, and don't mutate the array's length mid-loop.

Frequently asked questions

How does a for loop work in JavaScript?
It has three parts — initializer, condition and step. The body runs while the condition is true, and the step runs after each pass.
What is the difference between for and for...of?
A for loop uses a counter and gives you the index; for...of iterates the values directly, which is cleaner when you don't need the index.
How do I stop a for loop early?
Use break to exit the loop immediately, or continue to skip to the next iteration.
Should I use let or var in a for loop?
Use let. It scopes the counter to each iteration, which avoids classic bugs when callbacks capture the loop variable.