Iteration and For-Of Loops
Iteration
Iteration is a repeating portion of an algorithm. It repeats a fixed number of times, or keeps going until some condition is met.Suppose four measurements need adding up. Written out by hand, the same line appears over and over:
The for-of loop
Repetition loops are usually called for loops, because for is the keyword nearly every language uses to introduce them. JavaScript has more than one kind. The one that visits each VALUE of a sequence is the for-of loop.Arrays
An array is an ordered sequence of values, written as comma-separated values between SQUARE brackets. The AP reference sheet calls this a list; JavaScript calls the type an array. Here the two words mean the same thing.What the loop variable holds
On each pass the loop variable IS the next value. It is not a position number. On the first pass it is the first value, on the second pass the second value, and so on.Every console.log ends its line
console.log always finishes the line it prints, and JavaScript gives you no way to ask it to leave the line open. A loop that logs three values therefore prints three separate lines.To get one line instead, build a single string with + inside the loop, then log that string once after the loop has ended.
Looping over a string
A string is a sequence of characters, so for-of walks it one character at a time.The braces decide what repeats
Everything between the braces is the body, and the body runs on every pass. Anything written after the closing brace runs once, after the loop has finished. Moving one brace changes the whole output, so find the closing brace before you decide what repeats.| Loop header | The variable holds, in order | Passes |
|---|---|---|
for (const weight of weights) | 62, then 27, then 90 | 3 |
for (const letter of "sky") | s, then k, then y | 3 |
for (const item of []) | nothing at all | 0 |
The program below has one loop over an array and one over a string. Run it, then change it and run it again:
• Add a fourth station to the array.
• Change "train" to a longer word.
• Cut the line
console.log("End of the line"); and paste it directly above the closing brace of the first loop.const stations = ["Oak Street", "City Hall", "Riverside"];
for (const station of stations) {
console.log("Next station: " + station);
}
console.log("End of the line");
for (const letter of "train") {
console.log(letter);
}
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.