Iteration Methods
Iteration methods are one of two ways to do something to each of the elements of an array. The other, that we'll cover later, is using a for loop.
Given an Array, here are some ways you can use it.
Do Something to Each Item in the Array
In the code below, the greet function is used to define what to do. cats.forEach, where the value of cats is an Array, means do a thing to each of the items in the array.
let cats = ['Mark', 'Patches', 'Alvin'];function greet(name) {console.log("Hello, " + name);}cats.forEach(greet);
The version that uses iteration method, cats.forEach(greet), has the same effect as the following explicit code, that contains a line of code for each item of the Array:
greet(cats[0]);greet(cats[1]);greet(cats[2]);
The iteraton method has several advantages over the explicit version:
- If
catshad hundreds or thousands of items, it wouldn't be practical to write out thegreet(cats[_])lines (with each_replaced by a different number) for each one. This could happen if the value ofcatsis computed, or is read from a file or other external data source. - The code for the explicit version needs to be updated whenever the length of the array changes. It's not possible to make it work when the length of the array isn't known at the time that the code is written.
- The explicit version is prone to typos. It would be easy to write
greet(cats[0])twice in a row instead of updating the second line togreet(cats[1]).
The disadvantage of the iteration method is that it is more abstract (and can be more difficult to understand).
Try the code out here. As you step through the code, note how each time the greet function is entered, there is a new frame, in which the name parameter has a different value.
Transform an Array
[Under construction]