for
Loops
12.0. Overview
Computers are good at calculating, and computers are good at repeating things very quickly. The control structure that allows us to tell a computer how to repeat instructions is called a loop.
A conditional loop—the while
loop—is typically used when we don't know how many times something is going to be repeated. When a user plays a computer game, we ask them if they want to play again, and we'll keep looping over the game until they don't want to play anymore. That's a perfect example of a situation that requires using a while
loop.
We saw examples of a while
loop being used to count, also, with a variable i
going up from 0 to 9, or down from 5 to 0. We can use while
loops that way just fine, but there's another type of loop that is commonly used when we know how many times the loops is going to run.
This is the for
loop.
12.1. The for
Loop
In programming, sometimes you'll know exactly how many times a loop is supposed to repeat before it's finished. For a loop that counts from 0 to 9 (a total of 10 times), we could use a while
loop:
// while loop example let i = 0; while (i < 10) { console.log(i); i = i + 1; } console.log("All done!");
This process of counting a specified number of times is so common in computer science that most languages, including JavaScript, provide for a specialized definite loop called the for
loop.
The indexed for
loop
The for
loop is a definite loop structure that repeats a body of instruction a specified number of times.
// Counting up for (let i = 0; i < maxValue; i++) { <statement> <statement> <statement> } <Statement that is not part of the loop>
If someone were to ask you to write a program that called MultipleHelloWorlds
to print "Hello, world!" five times, you might write something like this:
document.write("Hello, world!" + "<br />"); document.write("Hello, world!" + "<br />"); document.write("Hello, world!" + "<br />"); document.write("Hello, world!" + "<br />"); document.write("Hello, world!" + "<br />");
Here's a better way to do that, using a for
loop:
for (let i = 0; i < 5; i++) { document.write("Hello, world!" + "<br />"); }
Being able to write a program to do something a fixed number of times is nice, but we don't want to have to rewrite the program every time the number changes. What if we wanted to have "Hello, world!" print a different number of times, depending on what the user wants?
Inputting values
Enter this code and run the program.
num = parseInt(prompt("How many times do you want to be greeted? ")) for (let i = 0; i < num; i++) { console.log(i + " Hello!"); } console.log("...and goodbye!");
12.2. Lists, and Looping through lists
12.2.0. Overview
One of the most powerful data structures in programming is the array
, a sequential list of items.
12.2.1. Lists
The array
(sometimes called a list in most other programming languages) is an incredibly useful and powerful data type. It allows us to refer to a collection of data using a single variable.
The list
data structure
A list
is a sequence of data values. Lists may be made up of any type of value: strings, ints, floats, even other lists. Lists are indicated with square brackets enclosing the items in the list, which are separated by commas.
myData = ['Richard','White','626-845-1235',50];
summerMonths = ["June","July","August"];
randNums = [3, 2.2, 14, -5, 0];
myFriends = ["Kathy","Dana","Gary"];
shoppingList = ["apples","bread","cheese"];
Individual items in a list can be referenced by referring to a single index value.
my_best_friend = my_friends[1];
Arrays are one of the single most powerful data structure in programming. We'll be using them a lot!
12.2.2. Using lists
12.2.2.0. Iterating through a list
How are lists so powerful? Just as we've used a for
loop to run through a range of numbers, we can easily set up a loop to run through a series of items in a list.
Two ways of going through a list
We actually have two different ways of going through a list. Which way you'll choose to write your list iteration depends on what you need to do.
Looping through a list with an index variable
You could run through the items in the list this way:
let shoppingList = ['apples','bread','cheese']; shoppingList.push['dumplings']; console.log("Don't forget to buy:"); for (let i = 0; i < shoppingList.length; i++) { console.log(shoppingList[i]); }
Here, the index i
changes as we go through the list, so each time we refer to shoppingList[i]
, we get a new value. This is the loop to use if you want to remember the location(s) of specific value(s) in your list as part of the program you're writing.
Looping through the list with an iterator
You can also go through all the items in the list this way, using iteration:
let shoppingList = ['apples','bread','cheese']; shoppingList.push['dumplings']; console.log("Don't forget to buy:"); for (item of shoppingList) { console.log(item); }
Just as in a for
loop with numbers, this loop will repeat: the first time through, item
will represent the first piece of data in the list shoppingList
("apples"), the second time through it will be "bread", and so on.
The advantage to this loop is that you don't need an index variable like i
to refer to each item in the list. The disadvantage is that this loop runs through each item once, from beginning to end. If you need more flexibility in your program, you'll need to use the index-strategy mentioned above to go through the loop.