Skip to main content

Command Palette

Search for a command to run...

JavaScript Array: map() Method

Updated
2 min read
JavaScript Array: map() Method
B

A developer documenting his knowledge. #keepLearning #keppGrowing

Sometimes we need to take an array and apply some method(s) to its elements so that we get a new array with modified elements.

Here in this module we will discuss the map() method of the JavaScript array.

Instead of manually run some conditions on an array, we can simply use the inbuilt array.map() method. This is a callback function that performs as a modifier of each element of an array and returns a new array with a set of new modified values. array.map() is a very popular method in JavaScript which performs a given condition on each of the elements of an array.

Points to remember:
1. map() does not change the original array.
2. map() will return a new array.

For example lets' take an array arr = [1,3,53,24,943,9]
now if we want a new array newArr where each element of arr will be multiplied by 2. Generally, in that case, We will perform a for loop throughout the array arr and will take each element, and we multiplied them by 2 and will create a new array.

var arr  = [1,3,53,24,943,9];

for(let i=0; i<arr.length;i++){
    arr[i] = arr[i]+2
}
console.log(arr): // -> [3, 5, 55, 26, 945, 11]

Achieving same by using arr.map()
We can achieve the same as the above result by using arr.map()

var arr  = [1,3,53,24,943,9];

let newArr = arr.map(function (x){
      return x+2;
});

console.log(newArr); -> [3, 5, 55, 26, 945, 11]

arr.map() using Arrow function:
Arrow function is an alternative process of a function expression. To do it in arrow function we have to do it in the following way

var arr  = [1,3,53,24,943,9];

var newArr = arr.map(x => x+2);
console.log(newArr); -> [3, 5, 55, 26, 945, 11];
console.log(arr): -> [1,3,53,24,943,9];

NOTE: So we can see, the map() method returns a new array with modified values. and old input array remains unchanged.

More from this blog

simplifying the learning of web development

19 posts

A Web Developer, on a mission to simplify the learning path of web development by sharing good and easy-to-understand content.