Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The for statement

Reference for the JavaScript for loop: initializer, condition and update expressions, per-iteration let bindings, optional parts, break and continue.

The for statement is the classic counting loop. Its header has three optional parts separated by semicolons: an initializer that runs once, a condition checked before every iteration, and an update expression that runs after each iteration. The loop ends when the condition becomes falsy.

Use it when you need an index, a custom step, or to walk backwards. When you only need each value of an array, for...of is shorter.

JavaScript
for (let i = 0; i < 5; i++) {
  console.log(i);
}

Try it

JS Counting, stepping and reversing

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Optional parts, break and closures

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
for (initializer; condition; update) {
  // body
}
Part Description
initializer Optional. An expression or a var / let declaration (several allowed, comma separated). Runs once.
condition Optional. Checked before each iteration; if omitted it is treated as true.
update Optional. An expression run after each iteration, before the next check.
body The statement that runs each time, usually a block.

Usage notes

  • Order of events: initializer, then condition, body, update, condition, body, update, until the condition fails.
  • let versus var. A let in the initializer is scoped to the loop and copied into a new binding on every iteration, so closures created in the body capture that iteration's value. With var all iterations share one variable. A const initializer fails if the update tries to change it.
  • break and continue. break ends the loop immediately; continue jumps to the update expression, then re-checks the condition. Labels let you affect an outer loop.
  • Off-by-one errors. Arrays are zero-based: use i < arr.length, not <=.
  • Floating point. Do not loop on x !== 1 with fractional steps; use < or an integer counter and compute the value from it.
  • Modifying what you iterate. Adding to an array while looping over arr.length can run forever. Cache the length or iterate a copy if you change the array.
  • Infinite loops. for (;;) loops forever unless the body breaks, returns or throws.
  • Alternatives. for...of for values, for...in for object keys, and array methods like forEach, map and filter for transformations.

Browser support

Supported in every JavaScript engine.