JavaScript for loop


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.


for ([initial-expression]; [condition]; [increment-expression])


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


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.


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

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);

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.

JavaScript: Tips of the Day

How do I redirect to another webpage?

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace.

// similar behavior as an HTTP redirect

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Ref: https://bit.ly/37JdWH8