JavaScript Array map()

Definition and Usage

map() The method creates a new array using the results of calling the function for each array element.

map() The method calls the provided function once for each element in the array in order.

Note:map() Does not execute the function for array elements without values.

Note:map() It will not change the original array.

Instance

Example 1

Returns an array of all square roots of the values in the original array:

var numbers = [4, 9, 16, 25];
var x = numbers.map(Math.sqrt);
document.getElementById("demo").innerHTML = x;

Try It Yourself

Example 2

Multiply all values in the array by 10:

var numbers = [65, 44, 12, 4];
var newarray = numbers.map(myFunction)
function myFunction(num) {
  return num * 10;
}
document.getElementById("demo").innerHTML = newarray;;

Try It Yourself

Example 3

Get the full name of each person in the array:

var persons = [
  {"firstname": "Malcom", "lastname": "Reynolds"},
  {"firstname": "Kaylee", "lastname": "Frye"},
  {"firstname": "Jayne", "lastname": "Cobb"}
];
function getFullName(item) {
  var fullname = [item.firstname,item.lastname].join(" ");
  return fullname;
}
function myFunction() {
  document.getElementById("demo").innerHTML = persons.map(getFullName);
}

Try It Yourself

Syntax

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

Parameter Values

Parameters Description
function(currentValue, index, arr) Required. The function to be run for each element in the array.

Function Parameters:

Parameters Description
currentValue Required. The value of the current element.
index Optional. The array index of the current element.
arr Optional. The array object that the current element belongs to.
thisValue

Optional. The value to be passed to the function to be used as its 'this' value.

If this parameter is empty, the value 'undefined' will be passed as its 'this' value.

Technical Details

Return Value: An array containing the result of the function provided for each element in the original array.
JavaScript Version: ECMAScript 5

Browser Support

The numbers in the table indicate the first browser version that fully supports this method.

All browsers fully support this method. map() Method:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9.0 Support Support Support Support

Related Pages

Tutorial:JavaScript Array

Tutorial:JavaScript Array Const

Tutorial:JavaScript Array Methods

Tutorial:JavaScript Sort Array

Tutorial:JavaScript Array Iteration