Array Iteration Methods: forEach and Map
Learn about the array iterations methods forEach and Map.
We'll cover the following...
Array iteration methods are methods that allow us to loop over an array and apply an operation to every item in the array. Every application of the operation to an item in the array is called an iteration.
JavaScript includes a number of array iteration methods that use callbacks to provide the instructions about what to do in each iteration. These methods always leave the original array unchanged, but often return a new array or value.
Efficient arrow functions: We’ll notice that arrow functions are frequently used to declare the callbacks in the following examples. They’re good candidates here because they’re short, can be written in a single line, and have an implicit return value.
The forEach()
method
The forEach()
method iterates over every item in an array and calls a callback function on every iteration. The callback function takes three parameters:
- The value of the current item in the array.
- The index of the current item in the array.
- A reference to the array itself.
If the method doesn’t use the index or array references, they don’t need to be specified. (Often only the value of the current item is provided as an argument.)
The following code shows an example that logs some information ...