for

Repeats a block of code with an initializer, condition, and update expression.

Since ES1 Spec ↗

Syntax

for (init; condition; update) {
  // ...
}

Examples

for (let i = 0; i < 3; i++) {
  console.log(i);
}
Output
0
1
2
let sum = 0;
for (let i = 1; i <= 5; i++) {
  sum += i;
}
console.log(sum);
Output
15
// Any clause may be omitted
let i = 0;
for (; i < 2; ) {
  console.log(i);
  i++;
}
Output
0
1

Notes

- Use `let` in the initializer to give each iteration its own binding, which matters for closures. - Use `break` to exit early and `continue` to skip to the next iteration. - For iterating values or object keys prefer `for...of` / `for...in`.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also