JavaScript: Loops
The reason computers are practical is that they can repeat through portions of code, or loop, as a programmer would say. If a programmer had to write the same piece of code over and over again, computers would probably never have caught on.
The main two looping forms utilized by programming languages and JavaScript are the “For” loop and the “While” loop. Both essentially serve the same purpose, but the way they operate is a little different. Loops run until an ending condition is met or the loop is escaped from. Loops make use of the logical and comparison operators discussed in the previous blog post.
The For Loop is set up with a counter and will increment after each iteration, until the end condition is met.
for example: Variable “x” will start at one and repeat the code in the brackets while “x” is less than 11.
var x=0;
for (x=0; x<10; x++)
{
document.write(“I will print this message 10 times.”);
}
The While Loop will run similarly to the For loop, with the exception that a counter is not implemented inside of the setup. With While loops, it is very easy to create an infinite loop if you don’t pay close attention to what you are doing.
for example:
var x = 0;
while(x<10)
{
document.write(“I will print out 10 times”);
x++; // If I was not here, the loop would go on an infinite number of times.
}
A less elegant want to get out of a loop is by using a Break statement. While it is functional, it should be used sparingly.
Assuming the loops above, if something like this code was in there, the loop would stop.
if(x == 2)
{
break;
}
The statements would be printed two times if this was above the print statement, and three times if it was below it.
If you want the loop to skip over a condition and not exit the loop, then a Continue statement should be utilized.
if(x==3)
{
continue;
}
else
{
document.write(“I will print this message 10 times.”);
}
The print statement would be executed 9 times, since it skipped printing when “x” was equal to three.
a252585f-58b0-454e-b4b1-1419d9c9c6b3|0|.0