DEV Community

Cover image for Array.prototype.map()
Hygor Costa
Hygor Costa

Posted on

Array.prototype.map()

**This post will explain about method map():

The map() method performs a function on each of the items in an array and as a return it creates a new array but does not change the original array.
 
This method calls the function once for each position(index) of the array.
 
 Does not execute the function for empty elements
 

Syntax:
array.map(function(currentValue, index, arr), thisValue)
Enter fullscreen mode Exit fullscreen mode

 
Argument :
currentValue – The value of element
index – Array position
arr – The array object the current element belongs to
   
    index and arr ( is optional, it is not necessary to have these statements for this                                                                                  method.) If this parameter is empty, the value "undefined" will be passed as its "this" value.

 
 

const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction);
 
 
function myFunction(num) {
  return num * 10;
}
 
Console.log(myFunction)
Enter fullscreen mode Exit fullscreen mode

 
 
X-RAY EXAMPLE:
 
In this example we have a constant declared “numbers” and its values (65,44,12,4).
 
Below we declare a new array as newArray and we have the method map + the function that will be executed on each of the items (index).
 
We have a function declared “myFunction” that will multiply each of the items(index) by 10, and this will return a new array, but also keeping the original array.
 
 After this execution we will have a new array with the result of the function.
 
We have another path to the same method.

const array1 = [1, 4, 9, 16];
 
const map1 = array1.map(x => x * 10);
 
console.log(map1);
// expected output: Array [10, 40, 90, 160]
Enter fullscreen mode Exit fullscreen mode

illustration:

Image description

 
 

Top comments (0)