‘Loops’ are a way of repeating the same block of code over and over until some condition is satisfied or the loop comes to an end.
WHILE loops
A ‘WHILE loop’ repeats a block of code while a condition is true. Like an IF statement, the condition is included in parentheses.
// After looping has finished the code carries on running from just after the closing brace ( } ) of the loop’s block. var i = 1;
while (i < 10) {
alert(i);
i = i + 1;
};
// i is now 10
FOR loops
A FOR loop is similar to an IF statement, but it combines three semicolon-separated pieces of information between the parentheses: initialisation, condition, and a final expression.
The initialisation 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.
// This gives us alert boxes containing the numbers 1 to 9 in order. // i++ is equivalent to i = i + 1. for (var i = 1; i < 10; i++) { alert(i); }
Use WHILE or FOR loops?
There is not a lot of difference between a WHILE and a FOR loop. The FOR loop can be more efficient, as it lets you set all three parameters in one line.
The main difference between the FOR’s and the WHILE’s is a matter of pragmatics: people usually use FOR when there is a known number of iterations, and use WHILE when the number of iterations is not known in advance.
Be wary with loops, though, if 'i' never fails the condition, the script will run forever and stop the form from running properly!
DO-WHILE
The DO-WHILE is different again, this loop executes the instructions once at the start, and afterwards it behaves just like the simple WHILE loop.
// This code will create alerts boxes for the numbers 1 to 10
var i = 1;
do {
alert(i)
i++;
} while (i < 10);
Comments
0 comments
Article is closed for comments.