Loops
The main reason computers work is that they loop through code. The computer wouldn’t be practical if it only went linearly and you had to keep repeating the same code. With a loop you can use the same section of code repeatedly, until an ending condition is met.
The two main loop styles are “for” loops and “while” loops.
With the “for” the instructions for starting, incrementing, and the condition check are all rolled into one statement. The “for” loop is used when you want a segment of code to run a certain number of times. This is where those comparison operators come into play. The code will run as long as the condition is true.
i.e.
var x = 0;
for(x = 0; x < 10; x++)
{
document.write(“Hello”);
}
In the case above, the code will be executed as long as the value of variable x is less 10.
“Hello” will be written ten times on the screen.
The “while” loop on the other hand will infinitely run through a block of code as long as the condition is met. The start condition and increment conditions are run outside of the loop condition.
i.e.
var x = 0;
while(x<10)
{
document.write(“Hello”);
x++;
}
This code will also print “Hello” ten times on the screen. But you can see how it is set up differently.
Alternatively, there is another way to get out of a loop. And that is the “break” statement.
Using this in your code will cause the loop to quit and continue with the rest of the code.
i.e.
var x = 0;
for(x = 0; x < 10; x++)
{
document.write(“Hello”);
if(x == 4)
{
break;
}
}
In this case, “Hello” will be written to the screen five times because the loop is broken on the fifth iteration.
Another handy statement is the “continue” statement. This causes the current loop to quit and start on the next loop iteration.
i.e.
var x = 0;
for(x = 0; x < 10; x++)
{
document.write(“Hello”);
if(x == 4)
{
continue;
}
}
In this case, “Hello” will be written to the screen nine times because the loop jumps a number when x is equal to four.