WHAT A LAMP Rotating Header Image

Loops of JavaScript

Loops in are used to execute the same block of code a specified number of times or while a specified condition is true.

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 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

The for is used when you know in advance how many times the script should run.

for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}

The while

The while is used when you want the to execute and continue executing while the specified condition is true.

while (var<=endvalue)
{
code to be executed
}

The do…while

The do…while is a variant of the while . This will always execute a block of code ONCE, and then it will repeat the as long as the specified condition is true. This will always be executed at least once, even if the condition is false, because the code is executed before the condition is tested.

do
{
code to be executed
}
while (var<=endvalue)

The above three loops are used very often while in coding. Look at the difference of them carefully.

Related posts

Comments are closed.