map() method in JavaScript
Let's see what MDN has to say:
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Here the calling array is the original array.
Let's see some examples in order to understand better:
let's see some examples
Example 1: Double the value of each element in an array and return a new array of modified elements.
//using arrow function
const numbersArray = [1, 5, 22, 40, 19]
const doublesArray = numbersArray.map(item => item*2)
console.log(doublesArray)
Result: [2, 10, 44, 80, 38]
//With normal functions
const numbersArray = [1, 5, 22, 40, 19]
function double(num){
return num*2;
}
const doublesArray = numbersArray.map(double)
console.log(doublesArray)
Result: [2, 10, 44, 80, 38]
In the above example, each and every element (or item) of the numbersArray will pass through the function double to return a new value. Further, all the returned values are combined to form a new array.
Note: map method does not mutate the original array. It returns a modified copy of the original array.