Traversing and Modifying a List
Two ways to traverse
A loop can walk through a list in two different ways. It can visit the VALUES, or it can visit the POSITIONS. JavaScript gives you one loop for each, and most of the time either will do.So far the two print the same thing. The difference shows up the moment you try to CHANGE the list.
Modifying a list
Here is code meant to triple every value in the list.The loop variable d holds a copy of the value, not the slot it came from. Assigning to d replaces that copy, and the list is never told. On the next pass d is handed the following value and the tripled number is gone.
Here is the same job done with an index loop. Compare it line by line against the version above.
| for-of | index loop | |
|---|---|---|
| The loop variable holds | a value | a position |
| Reading each item | yes | yes |
| Writing back into the list | no | yes |
| Knows where it is in the list | no | yes |
In the program below,
waits holds three waiting times in minutes, and both loops try to turn them into seconds. Run it, then change it and run it again:• Add a fourth waiting time to the array.
• Change the header of the index loop to
for (let i = 0; i < 2; i++).• Press Reset, then change
waits[i] = waits[i] * 60; to let seconds = waits[i] * 60;.let waits = [3, 10, 7];
for (let w of waits) {
w = w * 60;
}
console.log("After the for-of loop:", waits);
for (let i = 0; i < waits.length; i++) {
waits[i] = waits[i] * 60;
}
console.log("After the index loop:", waits);
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.
Building a list with push
You do not have to start from a list that already exists. Start from an empty one and let the loop grow it.The list starts with nothing in it and grows by one item on each pass. push adds to the end, and unlike an assignment to a loop variable, it does change the list. This is the accumulator pattern from the loops unit, with a list in place of a running total.