Array.map() method iterates through the array and calls a callback function on each element of the array. It collects the result of the callback function and returns a new array with results. It does not update the original array.
Syntax :
Array.map(callback(element, index, array), thisArguments)
The callback function accepts three parameters :
- element — This parameter holds the value of array element being processed.
- index — This parameter holds the index of array element being processed. It is optional.
- array — This parameter holds the array itself. It is also optional.
- thisArguments — This parameter holds the context to passed to the callback function.
Example 1 :
In the below example, each element of the array is multiplied and updated elements are returned.
let arrList = [1, 2, 3, 4, 5]; let updArr = arrList.map(function(element) { return element * 2; }); console.log(updArr);
Output :
[2, 4, 6, 8, 10]
Output : Example 2 :
In this example, we have used fat arrow syntax to implement the callback function. Each element of the array is added into the sum variable and returns the sum of array elements.
let arrList = [1, 2, 3, 4, 5]; let sum = 0; arrList.map((item) => { sum += item; }); console.log(sum);
Output :
15
Subscribe to our Youtube channel for more videos :