目录

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 »

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 »

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.


Syntax

array.map( function(currentValue, index, arr), thisValue)

Parameters

Parameter Description
function() Required.
A function to be run for each array element.
currentValue Required.
The value of the current element.
index Optional.
The index of the current element.
arr Optional.
The array of the current element.
thisValue Optional.
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 »

Browser Support

map() is an ECMAScript5 (ES5) feature.

ES5 (JavaScript 2009) fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11