Image of a cloud

Cloud Coding

Map Method in JS

By: Tristan Pedersen

Map Method in JS

The map() method is a higher order function which means it takes in a function as an argument.

map() creates a new array of the results of calling the given callback function on every element in the original array.

It calls a provided callback function once for each element in an array and constructs the new array based off of the results.

The callback function will only be invoked for indexes that have been assigned values.

It will not be invoked for empty slots in sparse arrays.

Ex.

const data [1, 2, 3, 4, 5]
const result = data.map((element) => {
   return element * 2;
})
// it will multiply each element in the array by two
console.log(result)
// output: [2, 4, 6, 8, 10]

Summary: The map() method has great use cases for when you are wanting to change an array as a whole. map() creates a new array populated with the results that the callback function had on each element in the original array. The map() method is an iterative method. It calls a provided callback function once for each element in an array and will construct a new array from the results. The callback function will only be invoked for indexes with values. It is not invoked for empty slots in sparse arrays.