Array Map Method in JavaScript

We use an array in Javascript to create a collection of elements. We declare an array in Javascript as:

let arr1 = [2, 5, 6, 3, 8, 9];

this is an array containing integer values. But we can create an array with string or decimal values as well.

let arr2 = ['a','b','c'];

or

let arr3 = [1.1,1.2,1.3];

Many times we want to execute some logic for every element in the array. We can execute logic for every element in the array using the array map method.

This method is called on the array instance and receives a function as a parameter.

The function accepts 1 required and 2 optional parameters.

  • Value The current element value. This is a required parameter.
  • Index The index corresponding to the element. This is an optional parameter.
  • Array The entire on which this method is called. This is an optional parameter.

Return Value

This method returns a new array with the transformed values , using the function:

For example, if we declare the array as:

Then if we call the map method on the array as:

arr1.map((val,i,arr)=>{console.log(val,i);});

Then we get the output of the element value and its index for all the elements in the array.

2 0
5 1
6 2
3 3
8 4
9 5

We can create

let arr1 = [1,2,3,4,5];
let arr2=arr1.map((val,i,arr)=>{return val*2;})
console.log(arr2);

Here we are updating every array element by multiplying it by 2. We get the following output.

[ 2, 4, 6, 8, 10 ]