We're live-coding on Twitch! Join us!

Basics

The map() method takes a callback method that performs an operation on the elements in the array. It returns a new array containing the resulting values of running the operation on each element. This method does not mutate the calling array.

let newArray = [1, 2, 3, 4, 5].map(function(number){
    return number * 2
})
// [2, 4, 6, 8, 10]

The .map() method:

  • Takes a callback function that is called once for each element.
  • Calls the callback function and gets the result of the operation run on the element
  • Returns a new array with the results> The .map() method creates a new array and doesn't mutate the old array.

Syntax

let newArray = oldArray.map(callback(element[, index[, array]])[, thisArg])

2 Parameters

callback This is the function that executes each of the elements of the array. The callback function is required and can take three parameters:

  • element: This is the element currently being executed - required.
  • index: This is the index of the current item - optional.
  • array: This is the array that is currently being processed - optional.

thisArg This is an argument passed to be used as the this value in the callback - optional

Returns an array

A new array with each value being the result of the callback function.

const numbers = [2, 4, 6, 8];
const squares = numbers.map(number => number * numbers);

console.log(squares);
// output: Array [4, 16, 36, 64]

Common Uses and Snippets

Creating a new array from the values contained in a calling array.

Reformatting the values contained within an array

Like this article? Follow @codebeast on Twitter