Java Reference
In-Depth Information
Loops
Loops will repeat a piece of code over and over again according to certain conditions.
while
Loops
We'll start by looking at a
while
loop. This will repeatedly run a block of code while a
certain condition is true and takes the following structure:
while (condition) {
do something
}
Here's an example that will count down from ten, alerting us with a line from the famous
song:
var bottles = 10;
while (bottles > 0){
alert("There were " + bottles + " green bottles, hanging
on the
↵
wall. And if one green bottle should accidently fall,
there'd be
↵
" + (bottles-1) + " green bottles hanging on the wall");
bottles--;
}
We start by declaring a variable called
bottles
. Any variables that are used in the loop
must be initialized before the loop is run, otherwise there will be an error when they are
mentioned.
The loop starts here with the
while
keyword and is followed by a condition and a block of
code. The condition in the example is that the number of bottles has to be greater than zero.
This basically means "keep repeating the block of code, as long as the number of bottles is
greater than zero".
