JavaScript Loops

This tutorial is part of a web programming course for people who have no programming experience.


You learned about one type of control structure in programming when we covered IF statements. IF statements control whether or not a code branch will be executed depending on certain conditions. Another type of control structure in programming is a loop.

A loop allows you to run a block of code repeatedly. Remember that a block of code is code that is enclosed within curly braces. There are a few different types of loops, and as you gain experience you'll learn which type will best meet your needs. For example, you use a 'for' loop to execute a block of code a specific number of times, and you can use a 'while' loop repeat a block of code while boolean expression remains true.

While Loops

A while loop will continue to repeat as long as a boolean expression evaluates to true. Let's start by looking at the syntax of a while loop:


while(boolean expression goes here){
  //this code will repeat until the boolean expression evaluates to false
}

It all starts with the while keyword. Then comes a boolean expression that is nested in parenthesis After the parenthesis comes a pair of curly braces (also known as a code block or code branch). The code inside the curly braces make up the 'body' of the loop. This code in the body of the loop will repeat until the boolean expression evaluates to false.

You might be wondering how the boolean expression turns from true to false while the loop is running. It's usually some code inside the body that will alter the result of the boolean expression. Take a look at this example:

var guess;

while(guess != "George Washington"){
  guess = prompt("Who was the first president of the U.S.?");
}

alert("CORRECT!");

If you run this example, you will be prompted to answer a question over and over until you enter the correct answer. The first statement in the code sample declares a variable named 'guees', but does not initialize it. The boolean expression in the while loop will evaluate to true, because the value of 'guess' is not initialized and therefore is not equal to "George Washington". Remember that the inequality operator ( != ) is used to confirm that two values are not equal, if they are indeed not equal then result of the booelan expression will be true. So the loop begins, and the code in the body executes. In this example, the body of the loop is just a single statement that assigns a value to 'guess' by prompting the user to enter the answer to the queston. When the code in the body finishes executing, the boolean expression is evaluated again. So if the user had just entered "George Washington" into the prompt, then the boolean expression would evaluate to false this time, which would cause cause the loop to end. When the loop is terminated the code will flow to the first statement after the body of the loop, which alerts the user that they have entered the correct answer. If the user enters a wrong answer into the prompt, then the boolean expression will continue to evaluate to true and the code in the body of the loop will repeatedly execute until the correct answer is entered.

Note that the number of loops in this example depends solely on the value of the 'guess' variable And inside the body of the loop, 'guess' is re-assigned a new value based on what the user enters into the prompt.

We can verbalize this loop by saying, 'repeat the loop while the value of guess is not equal to George Washington'. And this is why it's called a 'while' loop.

Before moving on to the next type of loop, note that looping is also called iterating. And each time the code in the loop body executes is said to be an iteration.

For Loops

'For' loops allow you to repeat code block a specific number of times. And they differ from while loops in an important way; they have a built-in counter. The syntax for a 'for' loop is a little more complicated than a while loop:

for(set up the counter; boolean expression  based on the counter; increment the counter){
  // this code will repeat until the boolean expression on the counter evaluates to false
}

There's a alot going on here, let's break it down. It starts with the keyword for and is followed by a pair of parenthesis. There are three things that go inside the parenthesis (separated by semi-colons), and together they determine how many iterations the loop will execute. Then we have a pair a curly braces (a code block), which contains the body of the loop.

Let's discuss what's going on inside the parenthesis. First we declare and initialize a variable that acts as the loops counter (it's usually referred to as the counter variable). The second part (after the first semi-colon) is a boolean expression that will be evaluated. As long as this expression evaluates to true, the loop will continue to iterate. The third part (which comes after the second semi-colon) specifies how to increment the counter variable when an iteration completes. Remember the increment operator (++) from a previous lesson, which increase the value stored in a variable by one. In most cases you'll see the counter variable incremented by one you can also increment the counter variable by any amount (for example: x+=2)

That's a lot to swallow all at once, let's take a look at a real example of a for loop to make sense of it.

for(var x = 1; x < 3; x++){
  console.log("looping...x is " + x);
}

In this example, 'x' is our counter variable and it is initialized to 1 when the loop begins. The boolean expression indicates that the loop should iterate as long as x is less than 3. The final part inside the parenthesis indicates that x should be incremented by 1 after the code inside the body executes. It always seemed odd to me that we increment the counter before the body of the loop, when it is actually incremented after the last statement inside the body.

In the body of the loop, we are simply logging a message that displays the current value of the counter variable.

During the first iteration, x has a value of 1 (because that is what it was initialized to). But when all the code inside the body finishes executing, x will be incremented from 1 to 2 (because the increment operator was used for the third part in the parenthesis). The flow of code then goes back up to the boolean expression, which will result in true (2 < 3), so the loop iterates again and executes the code in the body (the console log should show "2" during this iteration). After the code in the body completes x will be incremented to 3, and the flow of code goes back up to evaluate the boolean expression. But now, the boolean expression will result in false (3 < 3 is false), and the loop terminates. The flow of code will then immediately jump to the first statement after the body of the loop.

It definitely takes some practice to get the hang of for loops, but they are so common in programming that you will quickly have many opportunities to use them. There are other types of loops in JavaScript as well, but we won't get into them now.

Before we move on, let's try out some variations of for loops. Although it's rare, there are times when you want to increment the counter variable by more than 1. The next code sample shows a loop that starts at 0, loops until the counter is less than or equal to 100, and increments the counter by 5 at the end of each iteration.

for(var x = 0; x < 100; x+=5){
  console.log("looping...x is " + x);
}

The next sample shows a loop starts that starts at 10 and counts down to one. Notice that the counter variable is decremented by one with each iteration.

for(var x = 10; x > 0; x--){
  console.log("looping...x is " + x);
}

Loops and Arrays

For loops and arrays go hand-in-hand because you can use a for loop to iterate through each element in an array. The trick is to use the counter variable inside the body of the loop to specify the index of each element in the array. You can also make use of the length property in the boolean expression. In the code sample below, notice how the loop counter (the variable 'x') is used to fetch each element in the array as the loop iterates.

var names = ["Bob", "Betty", "Keith"];

for(var x = 0; x < names.length; x++){
  console.log(names[x] + " is at index " + x);
}

Note that the counter variable is initialized to 0, because the index numbers of an array start at 0. If you forget to set it to 0, and instead set it to 1, you'll inadvertantly skip the first element in the array. In the body of the loop, we retreive the 'current' element by using the counter variable as an index number.

The Current Element

I want to clear up some terminology so that you understand what I mean when I say 'current element' (which I do frequently when talking about loops). When looping through an array, the current element is the one that is processed within the body of the loop. This will change with each iteration of the loop. In the code sample above, the current element in the first iteration is the string "Bob". In the second iteration, the current element is "Betty". In the final iteration, the current element is "Keith". You'll often hear me say something like, "loop the array and in the body of the do such and such with the current element".

Processing Data With Loops

Loops are extremely powerful because they allow you to process large amounts of data (often in the blink of an eye). Consider this example, which demonstrates how a waiter could use a loop to total his/her daily tips for a week:

var dailyTips = [40, 80, 107, 92, 77];
var totalTips = 0;

for(var x = 0; x < dailyTips.length; x++){
	totalTips += dailyTips[x];
}

console.log("The total is: " + totalTips);

This is a very simple example, but hopefully it demonstrates how programs can process collections data.

Looping Through an Array of Objects

It's very useful to loop through an array of objects, and somehow process each one. Consider this example:

var dogs = [
    {name: "Brutus", breed:"Boxer", gender: "male", age:7, vaccinated:true},
    {name: "Fido", breed:"Pit Bull", gender: "female", age:3, vaccinated:true},
    {name: "Daisy", breed:"Labrador", gender: "female", age:2, vaccinated:true}
];

for(var x = 0; x < dogs.length; x++){
  console.log(dogs[x].name, dogs[x].breed, dogs[x].gender, dogs[x].age, dogs[x].vaccinated);
}

You can save yourself some typing by 'getting a handle' on the current element (assigning it to a variable) before writing your processing code:

for(var x = 0; x < dogs.length; x++){
  var d = dogs[x];
  console.log(d.name, d.breed, d.gender, d.age, d.vaccinated);
}

This is actually less work for the computer as well, it's a trick known as 'caching the current element'.

Searching for Elements in an Array

A common programming task is to see if a certain value is in an array. You can use a loop to iterate through an array and check to see if one of the elements has the value that you are looking for:

var numbers = [1,3,4,7,12,15,17,20];
var userInput = prompt("Enter a number");

for(var x = 0; x < numbers.length; x++){
	var currentNumber = numbers[x];
	console.log(currentNumber);
	if(currentNumber == userInput){
    	console.log("I found " + userInput + " at index " + x);
  	}
}

Breaking Out of Loops Early

In the previous code sample added code that logs each element in the array (even if it wasn't the one we were looking for). If you ran this code a few times you may have realized that the loop continues even after finding the number that matches the userInput. In many cases, it's not optimal to do this. If you find the element you are searching for, you can terminate the loop early by using a the break keyword. Let's add it to the previous example and run it again:

for(var x = 0; x < numbers.length; x++){
	var currentNumber = numbers[x];
	console.log(currentNumber);
	if(currentNumber == userInput){
    	console.log("I found " + userInput + " at index " + x);
    	break;
  	}
}

Now that we have added the break statement, the loop will terminate as soon as it finds the number that matches the user input.

We'll conclude this lesson by creating a program that searches an array of 'people' objects. It will prompt the user for the last name of a person, and then use a loop to search for that person in the array:

var people = [
	{firstName: "Bob", lastName: "Jones"},
	{firstName: "Sally", lastName: "Smith"},
	{firstName: "Betty", lastName: "Jenkins"},
	{firstName: "Tommy", lastName: "Green"}
];

var searchFor = prompt("Enter the last name of the person you would like to search for");
var matchingPerson;

for(var x = 0; x < people.length; x++){
  	var currentPerson = people[x];
  	if(currentPerson.lastName == searchFor){
  		matchingPerson = currentPerson;
	}
}

if(matchingPerson != undefined){
	alert(matchingPerson.firstName + " " + matchingPerson.lastName);
}else{
	alert(searchFor + " is not in our system");
}
NEXT LESSON: Events