for loop

A for loop starts with the for keyword which is followed by a set of parentheses with three statements inside that tells the loop how many times it should repeat.

for (var count = 1; count < 5; count += 1)

The first statement var count = 1 creates a variable named count and assigns it an initial value of 1.
This is the starting point for the number of times the loop repeats.

The next statement count < 5 tells the loop when to stop running, in our case then count is less than 5 which means that the loop will repeat four times.

The last statement count += 1 determines the rate at which the variable is changed and whether it gets larger or smaller each time.


for (var count = 1; count < 5; count += 1) {
     document.write("This is a JavaScript loop.");

The code you want the loop to execute has to be enclosed within curly brackets.
If the third statement will be changed to count += 3 for example, the loop will run only twice since first time the value of count is 1 then the second time the value will be 4 and the third time it will be 7 which is not less than 5.

You can create some kind of list style using the fact that the variable is going up by 1 each time.

for (var count = 1; count < 5; count += 1) {
     document.write(count + ". This is a JavaScript loop.");

Loops can be nested within other loops. Of course you can nest as many levels deep as you can handle.

for (var count = 1; count < 5; count += 1) {
     document.write(count+". This is a JavaScript loop.");
          for (var count2=1; count2<5; count2+=1) {
               document.write("This is the nested loop.");

You can nest different types of block inside one another. For example you can nest an if/else statement inside a for loop.

Leave a Reply