The map()
method creates a new array by performing a function on each array element.
The map()
method does not execute the function for array elements without values.
The map()
method does not change the original array.
This example multiplies each array value by 2:
Example
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2;
}
const numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2;
}
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
When a callback function uses only the value parameter, the index and array parameters can be omitted:
Example
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
const numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
Array.map()
is supported in all browsers except Internet Explorer 8 or earlier. Practice Excercise Practice now