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.
for (let i = 0; i < 5; i++) { console.log(i); }
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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.
letversusvar. Aletin 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. Withvarall iterations share one variable. Aconstinitializer fails if the update tries to change it.breakandcontinue.breakends the loop immediately;continuejumps 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 !== 1with 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.lengthcan 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...offor values,for...infor object keys, and array methods likeforEach,mapandfilterfor transformations.
Browser support
Supported in every JavaScript engine.