Javascript Array.map()

Basics

The map() is a method of Array class. It creates a new array with the results of calling a provided function on every element in the calling array.

Array.map Example

In example below, we have an array of numbers. Then we use map() method to create a new array of numbers that are two times larger than original numbers.

ArrayMap.js
var originalNumbers = [1, 2, 3, 4, 5];

const newNumbers = originalNumbers.map(number => number * 2);
        
console.log("originalNumbers: ", originalNumbers);      
console.log(“newNumbers: “, newNumbers);

Code Explanation

In line 1, we define an array of numbers. This is the original array and it will not change.

In line 3, we define a new variable called “newNumbers” that will hold the new array. The map() method will iterate through the originalNumbers array and performs method "number * 2" to each element of the array.

So first it takes the first element in originalArray that is 1 and multiplies it by 2. Then it adds the result 2 into the newNumbers array. After that it takes the next element 2 and multiplies it by 2 and adds it in the newNumbers array. Then it will continue and do the same to all the element in the originalNumbers array and adds the results in the newNumbers array. Number is a parameter that is given to map() method.

In line 5, we print the originalArray to console. It should result "originalNumbers: [1, 2, 3, 4, 5]” .

In line 6, we print the newArray to console. It should result "newNumbers: [2, 4, 6, 8, 10]".