Loops

This lesson is part of the Web Programming 1 Course.

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 (whether a boolean expression results in true or false). 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 (aka branch) 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. In this lesson we'll cover two of the most common and basic loops. And in another lesson we'll explore other loops.

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 is the 'body' of the loop
	//(this code will repeat until the boolean expression evaluates to false)

}

It all starts with the while keyword. Then comes a boolean expression, which is nested inside a pair of 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:

const secretPassword = "opensesame";
let passwordEntered;

while(passwordEntered != secretPassword){
  passwordEntered = prompt("Enter the secret password");
}

alert("You have successfully entered the secret password!");

If you run this example, you will be prompted to enter the secret password over and over until you get it right. The first statement in the code sample declares a constant that sets the secret password to 'opensesame'. The second statement declares a variable named passwordEntered, but does not initialize it. The boolean expression in the while loop will evaluate to true, because the value of the passwordEntered is not initialized, and therefore is not equal to the string secretPassword constant. Remember that the inequality operator ( != ) is used to check that two values are NOT equal. If they are indeed not equal then result of the boolean 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 passwordEntered by prompting the user to enter the password. When the code in the body finishes executing, the boolean expression is evaluated again. So, if the user enters 'opensesame' into the prompt, then the boolean expression would evaluate to false, which would cause the loop to end. When the loop is terminated the code will flow to the first statement that comes after the body of the loop, which in this case alerts the user that they have entered the correct password. 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 password is entered.

Note that the number of loops in this example depends solely on the value of the passwordEntered variable, which will be set to whatever the user enters into the prompt inside the body of the loop.

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

Here's another example of a while loop. In this example you declare a variable that stores a number and the loop will continue until the user enters that number.

const yearOfMoonLanding = 1969;
let userInput;

while(userInput != yearOfMoonLanding){

	userInput = parseInt(prompt("In what year did humans first land on the moon?"));
	
	if(userInput == yearOfMoonLanding){
		alert("CORRECT!");
	}else if(userInput < yearOfMoonLanding){
		alert("It was later, guess again.");
	}else if(userInput > yearOfMoonLanding){
		alert("It was earlier, guess again.");
	}else{
		alert("Invalid input, guess again.")
	}
}

The main thing that distinguishes while loops from the next type of loop that we'll discuss is that when writing the code, you don't know how many times the loop will repeat. In the last example,the loop will repeat until the user enters the correct number.

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

A for loop allows you to execute a code block a specific number of times. And they differ from while loops in an important way; they include a counter variable which is used to determine how many times the loop iterates. The syntax for a for loop is a little more complicated than a while loop:

for(/*set up the counter variable*/; /*boolean expression based on the counter*/; /*increment the counter*/){
  
	//This is the 'body' of the loop
	//(this code will repeat until the boolean expression on the counter evaluates to false)

}

Here's an example of a real for loop that counts from 1 to 5, and in the body of the loop, we simply log the counter variable:

for(let x = 1; x < 6; x++){
	console.log(x);
}

There's a a lot going on here, so 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 (they are separated by semi-colons):

  1. A counter variable is declared and initialized to a value of 1. You can use any variable name you want for the counter variable, but it's common for programmers to simply use x or i.
  2. A boolean expression is used to determine if the loop will continue to iterate.
    • If the expression results in true, the loop will continue to run (iterate).
    • If the expression results in false, the loop will terminate.
  3. A statement that increments (or decrements) the counter variable. In most cases the increment operator is used to increase the counter variable by 1 after each iteration. But you can increase or decrease the counter variable by any amount.

Then comes a pair a curly braces (a code block), which contains the body of the loop. The statements inside this code block will repeat until the loop terminates. Remember that the loop will terminate when the boolean expression results in false.

If you run this code and look in the console log, you should see 1,2,3,4,5.

Using the Debugger to Step Through a For Loop

To understand for loops, I find it extremely helpful to use the debugger in the browser's Developer Tools to observe the flow of code and how each statement executes. This is difficult to describe on paper, so be sure to follow along with the video.

At this point, the best course of action is to practice writing many variations of a for loop, which you will see in the video that accompanies this lesson. Here are some of the variations:

Note that these examples are not necessarily useful, but you'll soon learn how to write loops that do extremely powerful things.

Watch out for Infinite Loops!

If you're not careful, it's possible to write a loop so that the boolean expression never becomes false, which means that it will never terminate. When this occurs, the loop will continue to run until the browser window crashes or stops your program. Here's an example of an infinite loop:

// THIS IS AN INFINITE LOOP!!!
for(let x = 10; x > 0; x++){
	console.log(x);
}

Loops and Arrays

The real power of for loops can be seen when you use them with 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 counter variable (x) is used inside the body of the loop to specify the index number of each element in the array.

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

for(let 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 skip the first element in the array. Also note that the boolean expression, x < names.length, makes use of the 'length' property of the array.

The Current Element

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 through 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:

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

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

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

This is a very simple example, but it demonstrates how you can write programs that process large amounts of 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:

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

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

Inside the body of this loop, we log the properties of each dog object.

You could save yourself a little bit of typing by assigning the current element to a variable with a short name. Here is a variation of the previous loop that assigns the current element to a variable named d (for 'dog'):

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

This is not only less for you to type, it's 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 very common task for a program is to search through an array, looking for elements that match a certain condition. For the next code sample, assume that you have an array that contains the test scores for a student. And that you want to know if the student scored an A on any of the tests:

const testScores = ["B", "C", "A", "D", "B", "C"];

for(let x = 0; x < testScores.length; x++){
	if(testScores[x] == "A"){
		console.log("Found an A!!!");
	}
}

Breaking Out of a Loop Early

There are times when you want to terminate a loop before it completes all of its iterations. To do this, you use a break statement. In the previous code sample, the loop continued to iterate even after it had already found what we were looking for. We could add a break statement to terminate the loop like so:

for(let x = 0; x < testScores.length; x++){
	if(testScores[x] == "A"){
		console.log("Found an A!!!");
		break; // this will terminate the loop
	}
}

Skipping an Iteration in a Loop

You can skip iterations in a loop by using a continue statement. The continue statement is not commonly used, but there are some use cases for it. Here's an example of a loop that will iterate from 1 to 10 but skip 5:

for (let i = 1; i <= 10; i++) {
  if (i === 5) {
    continue; // this will skip to the next iteration
  }
  console.log(i);
}

When you run this code, you'll note that 5 is not included in the log output. This is because of the continue statement. As soon as a continue statement executes, the loop will skip any code that comes after this statement, and it immediately move on to the next iteration of the loop.

Summary

Loops are an incredibly important tool that can do many useful things in a program. In this lesson we covered the basics of loops, in the next lesson we'll dig deeper by using loops to solve various complex problems. We'll also learn about other types of loops.