JavaScript Loops

The JavaScript for loop statement allows you to create a loop with three optional expressions. The following illustrates the syntax of the for loop statement:

loop.png

JavaScript-for-Loop.png

1) Simple for loop examples The following example uses the for loop statement that shows the numbers from 1 to 5 in the Console window.

for (var counter = 1; counter < 5; counter++) {
    console.log('Inside the loop:' + counter);
}
console.log('Outside the loop:' + counter);

How it works.

  • First, declare a variable counter and initialize it to 1. Second, display the value of counter in the Console window if counter is less than 5. Third, increase the value of counter by one in each iteration of the loop.

2) The for loop without the initialization part example The following example uses a for loop that omits the initialization part:

var j = 1;
for (j = 1;  j < 10;  j += 2) {
    console.log(j);
}
output
1
3
5
7
9