Loops

Contact Us or call 1-877-932-8228
Loops

Loops

Loops let you run a block of code a certain number of times.

The while loop

A while loop is similar to an if statement, except that its body will keep executing until the condition evaluates to false.

while (conditional) {
	loopBody
}

The loopBody statement is what runs on every iteration. It can contain anything you want. You'll typically have multiple statements that need to be executed and so will wrap them in a block ({...}). If there is only a single statement, then the curly braces are not necessary, but recommended as a good coding practice. The same rule holds for the other looping tags below.

A Typical while Loop

var i = 0;
while (i < 100) {

	// This block will be executed 100 times
	console.log('Currently at ' + i);

	i++; // increment i

}

You'll notice that we're having to increment the counter within the loop's body. It is possible to combine the conditional and incrementer, like so:

A while Loop with a Combined Conditional and Incrementer

var i = 0;
while (++i <= 100) {
	// This block will be executed 100 times
	console.log('Currently at ' + i);
}

Notice that we're starting at 0 and using the prefix incrementer (++i).

The do ... while Loop

This is almost exactly the same as the while loop, except for the fact that the loop's body is executed at least once before the condition is tested.

do {
	loopBody
} while (conditional);

A do ... while Loop Example

This type of loop always executes the body at least once, since the test is performed after each iteration.

var i = 10;
do {
	alert(i--);
} while (i >= 0);
alert('Blastoff!');

do {
	// Even though the condition evaluates to false
	// this loop's body will still execute once.
	alert('Hi there!');
} while (false);

The for Loop

A for loop is made up of four statements and has the following structure:

for (
initialization
; 
conditional
; 
iteration
) {
	loopBody
}

The initialization statement is executed only once, before the loop starts. It gives you an opportunity to prepare or declare any variables.

The conditional statement is executed before each iteration, and its return value decides whether or not the loop is to continue. If the conditional statement evaluates to a falsey value then the loop stops.

The iteration statement is executed at the end of each iteration and gives you an opportunity to change the state of important variables. Typically, this will involve incrementing or decrementing a counter and thus bringing the loop ever closer to its end.

The loopBody statement is what runs on every iteration. It can contain anything you want. You'll typically have multiple statements that need to be executed and so will wrap them in a block ({...}). If there is only a single statement, then the curly braces are not necessary, but recommended as a good coding practice. The same rule holds for the other looping tags below.

// logs 'try 0', 'try 1', ..., 'try 4'
for (var i=0; i<5; i++) {
	console.log('try ' + i);
}

Note: In this example, even though we use the keyword var before the variable name i, this does not "scope" the variable i to the loop block. We'll discuss scope in depth later in this chapter.

The for ... in Loop

There is a special version of the for loop that iterates through the elements of an associative array (or, equivalently, the properties of an object).

for (loopVariable in object) {
	loopBody using loopVariable
}

This loops through the set of element names within object, so that loopVariable is each name in turn. The associated values would be retrieved as object[loopVariable].

var person = { firstName: 'Joe', lastName: 'Smith' };

for (var item in person) {
	console.log(item + ' is ' + person[item]);
	// Should log 'firstName is Joe' and 'lastName is Smith'
}

Breaking and Continuing

Usually, a loop's termination will result from the conditional statement not evaluating to true, but it is possible to stop a loop in its tracks from within the loop's body with the break statement.

Stopping a Loop

for (var i = 0; i < 10; i++) {
	if (something) {
		break;
	}
}

You may also want to continue the loop without executing more of the loop's body for this iteration. This is done using the continue statement.

Skipping to the Next Iteration of a Loop

for (var i = 0; i < 10; i++) {
	if (something) continue;

	// The following statement will only be executed
	// if the conditional 'something' has not been met
	console.log('I have been reached');
}
Next