The for statement is a loop executing kind of a statement used to pre-test code's flow conditions.

This type of a statement is the most popular loop execution statement. The reason for that is due to a fact that a single line of code does all three crucial parts of any loop iteration at once; in other words, a variable or variables get initialized, the expression set, and the iteration started, all at once. The example below explains it better:

for (variables initialization; expression; iteration) {



Or with the real numbers situation:

var counter = 5;

for (var i=0; i<counter; i++) {



Another advantage of a for loop is that it is very versatile; for instance the variables i and counter may be defined, in or out of the loop; or may even be omitted in which case the semicolons must not be excluded (i.e. for (; i<counter; ).

The forloop statement is called a pretesting because the expression (above: i<counter) is tested before the loop starts and if it fails, the loop will never initiate.


The example with for statement in JavaScript:


›› go to examples ››