JavaScript Array map()
Examples
Return a new array with the square root of all element values:
const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt)
Try it Yourself »
const newArr = numbers.map(Math.sqrt)
Multiply all the values in an array with 10:
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)
function myFunction(num) {
return num * 10;
}
Try it Yourself »
const newArr = numbers.map(myFunction)
function myFunction(num) {
return num * 10;
}
More examples below.
Description
map()
creates a new array from calling a
function for every array element.
map()
does not execute the function for empty elements.
map()
does not change the original array.
Array Iteration Methods:
Syntax
array.map(function(currentValue, index, arr), thisValue)
Parameters
Parameter
Description
function()
Required.
A function to be run for each array element.
A function to be run for each array element.
currentValue
Required.
The value of the current element.
The value of the current element.
index
Optional.
The index of the current element.
The index of the current element.
arr
Optional.
The array of the current element.
The array of the current element.
thisValue
Optional.
Default value
A value passed to the function to be used as its
Default value
undefined
.A value passed to the function to be used as its
this
value.Return Value
Type
Description
An array The results of a function for each array element.
More Examples
Get the full name for each person:
const persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
persons.map(getFullName);
function getFullName(item) {
return [item.firstname,item.lastname].join(" ");
}
Try it Yourself »
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
persons.map(getFullName);
function getFullName(item) {
return [item.firstname,item.lastname].join(" ");
}
Array Tutorials:
Browser Support
map()
is an ECMAScript5 (ES5 2009) feature.
JavaScript 2009 is supported in all browsers since July 2013:
Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
Sep 2012 | Sep 2012 | Apr 2013 | Jul 2012 | Jul 2013 |