for Loops

By: Dusty Arlia
Published on November 5, 2012
Last Updated on Thursday, July 09, 2015 at 11:07 PM
Total Updates: 6

A type of programming loop that is a little more compact then a while loop is called a for loop. A for loop is usually used to repeat a series of steps a certain number of times.

Here is the basic syntax of a for loop:

for (/* [initialization] | [condition] | [iteration] */) {
//the contents of the for loop that gets repeated

And here's an example of a for loop:

for (var beerBottles = 99; beerBottles > 0; beerBottles--) {
document.write(beerBottles + '  bottles of beer on the wall.<br />');

for loops start with the keyword for and then they have three different expressions inside a set of parentheses. First, the variable beerBottles is initialized and assigned the value 99. Then the condition comes next. Here the variable beerBottles must be greater than 0 for the loop to execute. If beerBottles is 0 and the condition is false, then the code between the curly braces ({}) is skipped. The last part inside the parentheses is the variable beerBottles getting reduced by 1 using the decrement operator (--). This ensures the condition will at some point become false, avoiding an infinite loop. The variable beerBottles gets reduced by 1 only after the loop runs (it does NOT get reduced before the first time through the loop). The code inside the pair of curly braces gets ran every time the condition remains true (remember the saying "true, do").