There are times you want the computer to repeat the same series of steps over and over.
For example, may want to change the color of 10000 elements in an array.
while loops repeat the code inside the brackets as long as the
condition
is true. Every time it finishes with the code inside the bracket, it tests the
condition
inside the parenthesis.
while (condition){
// statements;
}
var x = 0;
while( x < 10 ){
document.write(x + "<br>");
x = x + 1;
}
is equivalent to
document.write(0 + "<br>");
document.write(1 + "<br>");
document.write(2 + "<br>");
document.write(3 + "<br>");
document.write(4 + "<br>");
document.write(5 + "<br>");
document.write(6 + "<br>");
document.write(7 + "<br>");
document.write(8 + "<br>");
document.write(9 + "<br>");
When using while loops, it is important that you make sure that the condition you are testing for eventually turns to false or else you will have created an
infinite loop.
var num = 1;
while (num <= 4 ){
document.write(num + "<br>"); // this is an infinite loop
}
Loops are often used in conjunction with arrays. [
04_whileloop.html]
var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var counter = 0;
while (counter < days.length){
document.write(days[counter] + ', ');
counter++;
}