Name

Array.map() — compute new array elements from old

Availability

ECMAScript 5

Synopsis

array.map(f)
array.map(f, o)

Arguments

f

The function to invoke for each element of array. Its return values become elements of the returned array.

o

An optional value on which f is invoked.

Returns

A new array with elements computed by the function f.

Description

map() creates a new array with the same length as array, and computes the elements of this new array by passing the elements of array to the function f. map() loops through the indexes of array, in ascending order, and invokes f once for each element. For an index i, f is invoked with three arguments, and its return value is stored at index i of the newly created array:

a[i] = f(array[i], i, array)

Once map() has passed each element of array to f and has stored the results in the new array, it returns that new array.

See Array.forEach() for further details.

Example

[1,2,3].map(function(x) { return x*x; });  // => [1,4,9]

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.