w3resource

JavaScript for loop

Description

A JavaScript for loop executes a block of statements until a specified condition is true.

For loop creates a loop that allows us to specify three different expressions in a single line, enclosed in parentheses and separated by semicolons, followed by a group of statements executed in the loop.

The JavaScript for loop is similar to the Java and C for loop.

Syntax

for ([initial-expression]; [condition]; [increment-expression])
{
statements 
}

Parameters

initial-expression: Statement or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are local to the function, not to the loop.

condition: Evaluated on each pass through the loop. If this condition evaluates to true, the statements in the block are performed. This conditional test is optional. If omitted, the condition always evaluates to true.

increment-expression: Generally used to update or increment the counter variable.

statements: Block of statements that are executed as long as condition evaluates to true. This can be a single statement or multiple statements. Although not required, it is a good practice to indent these statements from the beginning of the for statement.

Pictorial Presentation:

javascript for loop

Example:

In the following web document for statement starts by declaring the variable r and initializing it to 1. It checks that r less than eleven and displays the variable r and sum of i stored in the variable z, after that r increases by 1.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>JavaScript for statement :  Example-1</title>
<link rel="stylesheet" type="text/css" href="example.css">
</head>
<body>
<h1>JavaScript : for statement</h1>
<p id="result">Output will be displayed here.</p>
<script src="for-statement-example1.js"></script>
</body>
</html>

JS Code

var r = 0;
var z = 0;
for (r = 1; r<11; r++) {
z = z + r;
var newParagraph = document.createElement("p");
var newText = document.createTextNode(r+' ---> '+z);
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph);
}

View the example in the browser

Practice the example online

See the Pen while-1 by w3resource (@w3resource) on CodePen.


Previous: JavaScript while loop
Next: JavaScript: label statement

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.