News & UpdatesProgrammingWeb programming Store My Projects

JavaScript Tutorial – 07 – Loops

JavaScript tutorials

The loop statements are used to execute a specific code block several times. In JavaScript, there are four kinds of loops: while, do-while, for, and for-in. As with the conditional if statement the curly brackets can be omitted if there is only one statement in the code block.

While loop

The while loop runs through the code block only if the condition is true and will continue looping for as long as the condition remains true.

var i = 0;
while (i < 10) { document.write(i++); }

Do-while loop

The do-while loop works the same as the while loop, except that it checks the condition after the code block and will therefore always execute at least once.

var j = 0;
do { document.write(j++); } while (j < 10);

For loop

The for loop is used to go through a code block a specific number of times. It takes three parameters. The first parameter is executed once before the loop starts and is commonly a counter declaration. The second parameter holds the condition for the loop and is checked before each iteration of the code block. The third parameter commonly contains an increment for the counter and is executed at the end of each iteration after the code block.

for (var k = 0; k < 10; k++) { document.write(k); }

In the for loop, either one of the parameters can be left out.

for (;;) { document.write("infinite loop"); }

For-in loop

The for-in statement gives an easy way of iterating through elements in an array or through properties in an object. On each iteration the key or index of the next property is assigned to the variable and the loop continues to iterate until it has gone through all members of the object.

var a = ["one","two","three"];
for (var p in a) { document.write(a[p]); }

Break and Continue

There are two special statements that can be used inside of loops. The break keyword ends the current loop and continue skips the rest of the current loop and continues at the beginning of the next iteration.

break;    // end loop
continue; // start next iteration
Recommended additional reading:
Sams - Teach Yourself JavaScript in 24 Hours