Loops
Loops are another group of control structures, normally used to keep your code smaller by evaluating a statement or collection of statements a specified number of times.
Let’s say we want to alert
a countdown from 10 to 0. Without loops, we’d have to write:
var i = 10; alert( i ); i--; // 9 alert( i ); i--; // 8 alert( i ); i--; // 7 alert( i ); i--; // 6 alert( i ); i--; // 5 alert( i ); i--; // 4 alert( i ); i--; // 3 alert( i ); i--; // 2 alert( i ); i--; // 1 alert( i ); i--; // 0 alert( i );
That’s 22 lines of code and a lot of repetition. Using loops we can perform the same task. First let’s see how we’d do it with a simple while
loop:
var i = 10; while ( i >= 0 ){ alert( i ); i--; }
Using while
, we were able to compress the whole thing down to five lines, which is pretty cool. What while
does is test the condition set in the argument and then perform the statements within its curly braces over and over until the condition is no longer met. In pseudocode, that looks like this:
initialize;while
(condition
){statement
;alter condition
; }
It is important to remember, when dealing with loops, that you need to pay attention to both your condition and how you alter your condition to make sure you loop will not execute ad infinitum. For example:
var i = 11; while( i > 10 ){ i++; } alert( i ); /* this statement is never reached because the while loop's condition is always met */
A similar loop type is do
...while
. The difference between do
...while
and while
is that a do
...while
loop ...
Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.