Javascript For loop

For loop in Javascript helps us to execute a task in a loop.

Example:

Lets print 1 to 5,

var a=1;

alert(a);

a=2;

alert(a);

a=3;

alert(a);

a=4;

alert(a);

a=5;

alert(a);

The above code would print 1 to 5.

Problem with above approach:

In the above approach, we have declared one variable a and we have assigned the value five times. It is time consuming and resource and effort consuming process. What if we are required to print 1 to 1000. It would become heavy process. So, We can get same result using for loop.

for(var a=1;a<=5;a++){

alert(a);

}

The above code would print 1 to 5. But in this approach, we have done with just three lines. We can get n number of results.

Note: For our understanding purpose, we are printing the result to the alert box but this is wrong approach. Alert is used to alert user.

Assignment:

Print 100 to 1 (hint: var a=100;a>=1;a–)