We're looking for a person or people to help audit MDN to find places we could speed up. Is this you or someone you know? Check out the RFP: https://mzl.la/2IHcMiE

for Redirect 1


Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.

Version Information

Implemented in: JavaScript 1.0, NES 2.0
ECMA Version: ECMA-262


for ([initialization]; [condition]; [final-expression])


An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements.


Example: Using for

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

for (var i = 0; i < 9; i++) {
   n += i;

Example: Using for without the statement section

The following for cycle calculates the offset position of a node in the [final-expression] section, and therefore it does not require the use of a statement or block statement section:

function showOffsetPos (sId) {
  var nLeft = 0, nTop = 0;

  for (var oItNode = document.getElementById(sId); oItNode; nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent);
  alert("Offset position of \"" + sId + "\" element:\n left: " + nLeft + "px;\n top: " + nTop + "px;");
Note: In this case, when you do not use the statement section, a semicolon is put immediately after the declaration of the cycle.

See also

Document Tags and Contributors

 Last updated by: Sheppy,