DEV Community

Cover image for Array.Map() - for mapping items in an array
Dillion Megida
Dillion Megida

Posted on • Edited on

Array.Map() - for mapping items in an array

This article is the start of a series where I explain different array methods, how they work, and use cases.

I'll be starting with the Map method.

Here's the video version: Array.map() YouTube

What is the Map method?

The map method of arrays is a higher-order function that loops through each item in the array, performs some operations on the item, and returns it to make up the resulting array.

As a higher-order function, it takes a function as an argument. During the loop, this function receives an item (and its index position in the array), does something with the item, and returns a new item that makes it to the new array.

The returned output of the map method is a new array containing the same number of items but with new items.

Syntax of the Map method

someArray.map(function(item, index, array) {
  // something with item and/or index
  // return new item
})
Enter fullscreen mode Exit fullscreen mode

The item argument is the item being looped on.

The index argument is the position in the array. For example, the first item has an index of 0, and the second, 1.

The array argument is the array itself.

Without the Map method

The map method is a declarative abstracted function that literally "maps through an array". Here's an example showing how you can map through an array without this method:

const array = [...]

const newArray = []

for(let i = 0, i < array.length, i++) {
  const item = array[i]
  const newItem = ?? // do something with item
  newArray.push(newItem)
}
Enter fullscreen mode Exit fullscreen mode

This loop approach is similar to what the map method does in the background.

One use case of the Map method

There are many use cases of the map method. The general idea is to map through the items in an array, do something with those items and return a new array.

But let us look at one use case.

For making an immutable duplicate of an array

Arrays in JavaScript are objects which are reference data types. What this means is that:

const array1 = [1, 2]
const array2 = array1

array2.push(5)
console.log(array2)
// [1, 2, 5]
console.log(array1)
// [1, 2, 5]
Enter fullscreen mode Exit fullscreen mode

Because it's a reference and not a direct value, modifying array2 also affects array1.

To create an immutable duplicate, you can use the map method like so:

const array1 = [1, 2]
const array2 = array1.map(item => item) // arrow functions

array2.push(5)
console.log(array2)
// [1, 2, 5]
console.log(array1)
// [1, 2]
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
satya_97 profile image
Satyabrat Sahoo

Nice alternative to Clone()

Collapse
 
dillionmegida profile image
Dillion Megida

Yes, every nice