The for statement is a pretest loop.
for loop has the capabilities of variable initialization before entering the loop.
It also defines postloop code. Here's the syntax:
for (initialization; expression; post-loop-expression)
statement
And here's an example:
var count = 10; for (var i=0; i < count; i++){ console.log(i); }
This code defines a variable i that begins with the value 0.
The for loop is entered only if the conditional expression (i < count) evaluates to true.
If the body is executed, the postloop expression is also executed, iterating the variable i.
This for loop is the same as the following while loop:
var count = 10; var i = 0; while (i < count){ console.log(i); i++; }
The for loop encapsulates the loop-related code into a single location.
The loop controlling variable i can be defined outside the initialization:
var count = 10; var i; for (i=0; i < count; i++){ console.log(i); }
The variable i defined inside the loop is accessible outside the loop as well. For example:
var count = 10; for (var i=0; i < count; i++){ console.log(i); } console.log(i); //10
In this example, it displays the final value of the variable i after the loop has completed.
The initialization, control expression, and postloop expression are all optional.
You can create an infinite loop by omitting all three, like this:
for (;;) { //infinite loop doSomething(); }
Including only the control expression turns a for loop into a while loop:
var count = 10; var i = 0; for (; i < count; ){ console.log(i); i++; }