JavaScript map()
performing an operation on each element in an array
Motivation
Suppose we have an array and we wish to go through its elements, then perform the same operation on those elements...
We could use the built-in map()
function to iterate and transform:
Addition
In addition to the current element of the iteration, the map
method also has two optional parameters:
the
index
of the current elementthe original
array
showing all the elements
For example, we could provide more detail to the message logged to the console:
Here we have to include the return
statement because we have more than one line in the function!
Logging the original grades array only in the first iteration with that if
statement, this will log:
Summary
Remember that map()
:
returns the values into a new array
the length of the new array will always be equal to the original array
does not modify the original array
Last updated