The map()
method returns the new array after processing each element for the given array.
It accepts a callback function, which has currentItem
as a mandatory parameter. We can hold this currentItem
and process it as we like.
const newArrayName = oldArray.map(callbackFun(currentItem, currentIndex, array))
The map()
method takes callbackFun
as a parameter, and this callback function takes currentItem
, currentIndex
, and an array
as parameters.
The map()
method returns a new array with each element resulting from the callback function.
Let's look at an example of using the map to loop through an array. In the following example, we'll get the square of each number present inside the array.
Let's look at the code below:
const nums = [1, 2, 3, 4];// pass a callback function to mapconst squares = nums.map(x => x ** 2);console.log(squares);
In the above code snippet:
nums
.nums
using the map()
method and calculate the square of each element in the array nums
. We then store the returned new array in the variable squares
.squares
to the console.