|
| |
JavaScript for loop |
Like any other language JavaScript for loop is one of the important built in functions to develop scripts. For loop in JavaScript is similar to for loop in C or PHP language. Other scripting languages have also similar For loops like ASP for Next loop, PHP for loop etc.
For loop in client side JavaScript has three parts in its declaration. The first part initialize a variable, the second part checks the condition and the third part gives the steps in which the variable will change value. Here is the syntax.
For( initialization; condition; step ; ){
Statement
}
We can print number 1 to 10 by using for loop.
for (var x = 1; x <= 10; x++)
{
document.write (x+"<br>");
}
In the above code we have added one line break after each step of printing of number so the numbers will be displayed vertically.
Now let us try to display numbers starting from 10 to 0
for (var x = 10; x >= 0; x--)
{
document.write (x+"<br>")
}
In the first example x value is increased by 1 starting from 1 and in second example x value is decreased by 1 starting from 10
We can come out of the loop by using break statement inside the loop. Let us use one if condition to break the loop once x value reaches 5 . Here is the code with break statement.
for (var x = 1; x <= 10; x++)
{
document.write (x+"<br>");
if(x >5){break;}
}
The above code will display number 1 to 6 vertically. You can see once the value of x reaches 6 the if condition returns true and breaks the for loop.
| |
| Subscribe |
|
Submit your email address and receive
article and product notifications. Your email is safe with us.
|
|
|
|