Loops of JavaScript
Posted by David on April 3rd, 2007 filed in JavaScriptLoops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.
JavaScript Loops
Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In JavaScript there are two different kind of loops:
* for - loops through a block of code a specified number of times
* while - loops through a block of code while a specified condition is true
The for Loop
The for loop is used when you know in advance how many times the script should run.
{
code to be executed
}
The while loop
The while loop is used when you want the loop to execute and continue executing while the specified condition is true.
{
code to be executed
}
The do…while Loop
The do…while loop is a variant of the while loop. This loop will always execute a block of code ONCE, and then it will repeat the loop as long as the specified condition is true. This loop will always be executed at least once, even if the condition is false, because the code is executed before the condition is tested.
{
code to be executed
}
while (var<=endvalue)
The above three loops are used very often while in JavaScript coding. Look at the difference of them carefully.