The main strength of any programming language is its ability to process blocks of code repeatedly. Computers are especially adept at perfoming repeated calculations. JavaScript, like other programming languages, provides us with loop. Statements placed inside loops are executed a set number of times... or even infinitely.
We'll look at the for loop in this session. The while and do...while will be explained in the next session.
Here is the format of a for loop:
for (Initialization statements; Condition; Updation statements)
{
...
statements
...
}
When the JavaScript interpreter comes across a for loop, it executes the initialization statements and then checks the condition. Only when the condition returns 'true', the interpreter enters the loop. After the first iteration, the updation statements are executed and then the condition is evaluated again. This continues till the condition returns 'false' and the loop stops.
Some important points to note are:
We can use a for loop to print digits 1 to 10 in an alert box.
var msg = "";
for (var x = 1; x <= 10; x++)
{
msg = msg + x + "\n";
}
alert(msg);
First, the variable x is initialized to 1, the condition is then evaluated. Since x is less than equal to 10, the statements inside the for loop are executed. The JavaScript interpreter then runs the updation statement that adds 1 to variable x. The condition is again checked. This goes on till the value of x becomes larger than 10. At this point, the statement immediately following the for loop is executed.
var msg = "";
var res = "0";
for (var x = 1; x <= 12; x++)
{
res = 12 * x;
msg = msg + "12 X " + x + " = " + res + "\n";
}
alert(msg);
![]()
for (a = 0; a <= 10; a = a + 2)
{
... statements ...
}
for (b = 20; b <= 10; b++)
{
... statements ...
}
var y = 0;
for (x = 0; x <= 5; x++, y = y + 50)
{
y = y + 10;
}
alert("The value of y is " + y);
Page contents: Javascript for loop - repeating with javascript for loop - understanding the javascript for loop statement
Comments, questions, feedback... whatever!