HTML Dog
Skip to navigation

Looping

Loops are a way of repeating the same block of code over and over. They’re incredibly useful, and are used, for example, to carry out an action on every item in an array (we will come to arrays later) or in searching.

Two of the most common loops are while loops and for loops. They combine a conditional and a block, running the block over and over until the logic of the conditional is no longer true, or until you force them to stop.

While

A while loop repeats a block of code while a condition is true. Like an if statement, the condition is found in parentheses.


var i = 1;
while (i < 10) {
    alert(i);
    i = i + 1;
}
// i is now 10

After looping has finished the code carries on running from just after the closing brace (“}”) of the loop’s block.

For

A for loop is similar to an if statement, but it combines three semicolon-separated pieces information between the parentheses: initialization, condition and a final expression.

The initialization part is for creating a variable to let you track how far through the loop you are - like i in the while example; the condition is where the looping logic goes - the same as the condition in the while example; and the final expression is run at the end of every loop.


for (var i = 1; i < 10; i++) {
    alert(i);
}

This gives us alert boxes containing the numbers 1 to 10 in order.