Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

for

BaselineWidely available

Thefor statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually ablock statement) to be executed in the loop.

Try it

let str = "";for (let i = 0; i < 9; i++) {  str += i;}console.log(str);// Expected output: "012345678"

Syntax

js
for (initialization; condition; afterthought)  statement
initializationOptional

An expression (includingassignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables withvar orlet keywords. Variables declared withvar are not local to the loop, i.e., they are in the same scope thefor loop is in. Variables declared withlet are local to the statement.

The result of this expression is discarded.

conditionOptional

An expression to be evaluated before each loop iteration. If this expressionevaluates to true,statement is executed. If the expressionevaluates to false, execution exits the loop and goes to the first statement after thefor construct.

This conditional test is optional. If omitted, the condition always evaluates to true.

afterthoughtOptional

An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation ofcondition. Generally used to update or increment the counter variable.

statement

A statement that is executed as long as the condition evaluates to true. You can use ablock statement to execute multiple statements. To execute no statement within the loop, use anempty statement (;).

Description

Like other looping statements, you can usecontrol flow statements insidestatement:

  • break stopsstatement execution and goes to the first statement after the loop.
  • continue stopsstatement execution and re-evaluatesafterthought thencondition.

Examples

Using for

The followingfor statement starts by declaring the variablei and initializing it to0. It checks thati is less than nine, performs the two succeeding statements, and incrementsi by 1 after each pass through the loop.

js
for (let i = 0; i < 9; i++) {  console.log(i);  // more statements}

Initialization block syntax

The initialization block accepts both expressions and variable declarations. However, expressions cannot use thein operator unparenthesized, because that is ambiguous with afor...in loop.

js
for (let i = "start" in window ? window.start : 0; i < 9; i++) {  console.log(i);}// SyntaxError: 'for-in' loop variable declaration may not have an initializer.
js
// Parenthesize the whole initializerfor (let i = ("start" in window ? window.start : 0); i < 9; i++) {  console.log(i);}// Parenthesize the `in` expressionfor (let i = ("start" in window) ? window.start : 0; i < 9; i++) {  console.log(i);}

Optional for expressions

All three expressions in the head of thefor loop are optional. For example, it is not required to use theinitialization block to initialize variables:

js
let i = 0;for (; i < 9; i++) {  console.log(i);  // more statements}

Like theinitialization block, thecondition part is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

js
for (let i = 0; ; i++) {  console.log(i);  if (i > 3) break;  // more statements}

You can also omit all three expressions. Again, make sure to use abreak statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

js
let i = 0;for (;;) {  if (i > 3) break;  console.log(i);  i++;}

However, in the case where you are not fully using all three expression positions — especially if you are not declaring variables with the first expression but mutating something in the upper scope — consider using awhile loop instead, which makes the intention clearer.

js
let i = 0;while (i <= 3) {  console.log(i);  i++;}

Lexical declarations in the initialization block

Declaring a variable within the initialization block has important differences from declaring it in the upperscope, especially when creating aclosure within the loop body. For example, for the code below:

js
for (let i = 0; i < 3; i++) {  setTimeout(() => {    console.log(i);  }, 1000);}

It logs0,1, and2, as expected. However, if the variable is defined in the upper scope:

js
let i = 0;for (; i < 3; i++) {  setTimeout(() => {    console.log(i);  }, 1000);}

It logs3,3, and3. The reason is that eachsetTimeout creates a new closure that closes over thei variable, but if thei is not scoped to the loop body, all closures will reference the same variable when they eventually get called — and due to the asynchronous nature ofsetTimeout(), it will happen after the loop has already exited, causing the value ofi in all queued callbacks' bodies to have the value of3.

This also happens if you use avar statement as the initialization, because variables declared withvar are only function-scoped, but not lexically scoped (i.e., they can't be scoped to the loop body).

js
for (var i = 0; i < 3; i++) {  setTimeout(() => {    console.log(i);  }, 1000);}// Logs 3, 3, 3

The scoping effect of the initialization block can be understood as if the declaration happens within the loop body, but just happens to be accessible within thecondition andafterthought parts. More precisely,let declarations are special-cased byfor loops — ifinitialization is alet declaration, then every time, after the loop body is evaluated, the following happens:

  1. A new lexical scope is created with newlet-declared variables.
  2. The binding values from the last iteration are used to re-initialize the new variables.
  3. afterthought is evaluated in the new scope.

So re-assigning the new variables withinafterthought does not affect the bindings from the previous iteration.

A new lexical scope is also created afterinitialization, just beforecondition is evaluated for the first time. These details can be observed by creating closures, which allow to get hold of a binding at any particular point. For example, in this code a closure created within theinitialization section does not get updated by re-assignments ofi in theafterthought:

js
for (let i = 0, getI = () => i; i < 3; i++) {  console.log(getI());}// Logs 0, 0, 0

This does not log "0, 1, 2", like what would happen ifgetI is declared in the loop body. This is becausegetI is not re-evaluated on each iteration — rather, the function is created once and closes over thei variable, which refers to the variable declared when the loop was first initialized. Subsequent updates to the value ofi actually create new variables calledi, whichgetI does not see. A way to fix this is to re-computegetI every timei updates:

js
for (let i = 0, getI = () => i; i < 3; i++, getI = () => i) {  console.log(getI());}// Logs 0, 1, 2

Thei variable inside theinitialization is distinct from thei variable inside every iteration, including the first. So, in this example,getI returns 0, even though the value ofi inside the iteration is incremented beforehand:

js
for (let i = 0, getI = () => i; i < 3; ) {  i++;  console.log(getI());}// Logs 0, 0, 0

In fact, you can capture this initial binding of thei variable and re-assign it later, and this updated value will not be visible to the loop body, which sees the next new binding ofi.

js
for (  let i = 0, getI = () => i, incrementI = () => i++;  getI() < 3;  incrementI()) {  console.log(i);}// Logs 0, 0, 0

This logs "0, 0, 0", because thei variable in each loop evaluation is actually a separate variable, butgetI andincrementI both read and write theinitial binding ofi, not what was subsequently declared.

Using for without a body

The followingfor cycle calculates the offset position of a node in theafterthought section, and therefore it does not require the use of astatement section, a semicolon is used instead.

js
function showOffsetPos(id) {  let left = 0;  let top = 0;  for (    let itNode = document.getElementById(id); // initialization    itNode; // condition    left += itNode.offsetLeft,      top += itNode.offsetTop,      itNode = itNode.offsetParent // afterthought  ); // semicolon  console.log(    `Offset position of "${id}" element:left: ${left}px;top: ${top}px;`,  );}showOffsetPos("content");// Logs:// Offset position of "content" element:// left: 0px;// top: 153px;

Note that the semicolon after thefor statement is mandatory, because it stands as anempty statement. Otherwise, thefor statement acquires the followingconsole.log line as itsstatement section, which makes thelog execute multiple times.

Using for with two iterating variables

You can create two counters that are updated simultaneously in a for loop using thecomma operator. Multiplelet andvar declarations can also be joined with commas.

js
const arr = [1, 2, 3, 4, 5, 6];for (let l = 0, r = arr.length - 1; l < r; l++, r--) {  console.log(arr[l], arr[r]);}// 1 6// 2 5// 3 4

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-for-statement

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp