JavaScript Tutorial





Español Français 中文 Deutsch Portuguese Japanese nederlands
   
 
Java-Script Tutorial
Introduction Introduction
Variables Variables
Operators Operators
Statements Statements
Loops Loops
Functions Functions
Objects Objects
Arrays Arrays
Cookies JS Cookies
Browser Objects Browser Objects
Form DOM Form DOM
Style Objects DOM Style Objects
Forums Ask Your Doubts
Scraps More about Javascript
Feedback Feedback
 




For loop Code


Tutorials »Javascript »

Topic

Using 'for' loop in javascript?
I want to execute the same set of statements numerous time based on a incremental or decremental value?



Explanation

for LOOP:
        As we state it, for loop is a looping syntax.
A set of statements are executed as a loop until a condition is satisfied, the condition is based on an incremental or decremental counter. In other words "Looping statements in javascript are used to execute the same set of code a specified number of times".

Syntax:
for(intialvalue; condition; increment)
{
     // set of statements that will be executed
}


As defined in the syntax, for loop takes three parameters, the initial value (e.g i=0), condition - the statements inside "for" will be executed until this condition is satisfied (e.g i<7), increment - this is where we set the initial value to be increased or decreased after each loop.
All the three parameters are separated by semicolon ";".

For an example, we will consider a situation where we want to add all numbers between one and ten.
Example Code:
<script language="javascript">
var i=0; var total=0;
for(i=1; i<11; i++)
{
total = total+i;
}
document.write("--------- The total ------: "+total);
</script>


Result:

The example worked as follows,
a) Initially we created the for loop by setting variable i as 1.
b) then we set the condition that the loop should execute till i is less than 11 (i<11).
c) We made the variable to be incremented at the end of each loop (i++)

First loop: i=0, i<11 is true so the statement is executed, now the total becomes 0+1=1 and i is incremented to 2.

Second loop: now i=1, i<11 is true so the statement is executed, now the total becomes 1+2=3 and i is incremented to 2.

this continues till i=11
Last loop: now i=11, i<11 becomes false and the loop ends here.

Note: i++ increments the value at the end on the loop, while ++i to increase the value of i at the start of the loop.





A Note
Javascript (JS) is one of the most used languages in the world. Some times spelled as Java Script. Hope you enjoy this tutorial. Do send your feedback or suggestions on this javascript or java script tutorial. This is a copyright content.

Other Links

web hosting