Skip to content

for

In JavaScript, the for keyword starts a loop that runs an initializer once, then repeats its body while a condition stays true, running an update expression after each pass. All three parts of the head are optional. A missing condition counts as true, so for (;;) runs until a break or return ends it. A continue statement skips to the update.

A counter declared with let gets a fresh binding for each iteration, so a closure created in the body keeps that iteration’s value. A var counter is one binding shared by every iteration. A const counter throws a TypeError when the update tries to change it.

The same keyword starts three more loops. The for...of loop, added in ES2015, walks the values of an iterable and is covered under of. The for...in loop enumerates an object’s enumerable string keys, including inherited ones, and is covered under in. The for await...of loop, added in ES2018, consumes async iterables wherever await is allowed.

JavaScript for Keyword Syntax

The for keyword starts four kinds of loops:

Language: JavaScript Syntax
for ([<initialization>]; [<condition>]; [<afterthought>]) <statement>

for (<declaration> of <iterable>) <statement>
for (<declaration> in <object>) <statement>
for await (<declaration> of <asyncIterable>) <statement>

The <declaration> is a const, let, or var binding, or an existing variable or property.

JavaScript for Keyword Examples

A classic for loop adds up the prices with a counter variable:

Language: JavaScript
> const prices = [19.99, 5, 42.5];
undefined
> let total = 0;
undefined

> for (let i = 0; i < prices.length; i++) {
…   total += prices[i];
… }
67.49

The loop tests i before each pass and increments it after each one. The REPL echoes the value of the last statement the body ran.

Each iteration of a let counter has its own binding, which the closures below capture:

Language: JavaScript
> const readers = [];
undefined

> for (let i = 0; i < 3; i++) {
…   readers.push(() => i);
… }
3

> readers.map((read) => read())
[ 0, 1, 2 ]

With var i in the head, all three functions would share one binding and return 3.

JavaScript for Keyword Use Cases

  • Counting through a range of numbers or array indexes
  • Stepping through values at a custom interval or in reverse
  • Updating several counters together in one loop head
  • Looping until a break fires, with for (;;)

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 4, 2026