The JavaScript for statement
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
<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
letso each iteration is correctly scoped, especially around closures. - Use
breakto exit early andcontinueto skip an iteration. - Prefer for...of or forEach() when you don't actually need the index.
- Avoid recomputing things like
arr.lengthneedlessly, and don't mutate the array's length mid-loop.
Frequently asked questions
How does a for loop work in JavaScript?
What is the difference between for and for...of?
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?
break to exit the loop immediately, or continue to skip to the next iteration.