- Function- a function to be run on each array element.
- currentValue – the value of the element of current index.
- index – It is optional. The index of the current element.
- arr – It is optional. It denotes the array of the current element.
- thisValue – It is optional. Its default value is undefined
For example –
const arr1 = [4,9,16]; // Pass a function to map const map1 = arr2.map(x => Math.sqrt(x)); console.log(map1); // Expected output: Array [2,3,4]
The map() method is an iterative method. The map() method is a method of copying. It does not change this. However, the function provided as a callback can mutate the array. The length of the array is saved way before the first invocation of the callback function and will not go to any elements added beyond the array’s initial length when the call to map() starts. Modifications of already-visited indexes or elements do not cause e callback to be invoked again. If an already existing, yet-unvisited element or index of the array is modified by callback, its value passed in the callback will be the value at the time for which the element gets visited. Deleted elements are not visited.
Below is the code for mapping an array of numbers to their doubles ( 2*x)
const numbers = [1, 4, 9]; const roots = numbers.map((num) => num*2); // doubles are now [2,4,6] // numbers are still [1,2,3]