The map()
method is a fantastic
tool that helps us change the values
in an array without changing
the original array.
It allows us to create a new array
with modified elements easily.
Let us look at an example where
we have a list of numbers: [2, 4, 6]
Our goal is to generate a new list
by adding 1 to each element of
the given list.
In the code above, we defined
a function called createOddNumber()
.
This function takes a number and
returns that number incremented by 1.
Then, we use the map()
method to
call this function on each element
of the evenNumbers
array and
create a new array oddNumbers
with the results.
Let us make our code even cleaner
by moving the function definition
within the map()
method by passing
an anonymous function as the
callback to the map()
method.
In the improved version, we also
used the shorthand method for arrow
function without needing to specify
the return keyword.
It's like using a shortcut to create
the new oddNumbers
array
and
the result is the same as before.
Note:
The map()
method returns an array,
while forEach()
does not.
Knowing this distinction is helpful
when you choose the right method for your task.