How to Use the Array map() Method in JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to use the array map() method in JavaScript.

The map() method

The map method can perform the specified processing on all the data in the array and create a new array.
For example, if you have an array of product names and prices, use this method to halve the prices of all products.

The syntax is below.

// Arrow function
map((element) => { /* ... */ })
map((element, index) => { /* ... */ })
map((element, index, array) => { /* ... */ })

// Callback function
map(callbackFn)
map(callbackFn, thisArg)

// Inline callback function
map(function(element) { /* ... */ })
map(function(element, index) { /* ... */ })
map(function(element, index, array){ /* ... */ })
map(function(element, index, array) { /* ... */ }, thisArg)

Pass the function that processes the array data to the first argument of the map method

The usage of the callback function of the map method is as follows.

const array1 = [1, 2, 3, 4];
const array2 = array1.map(x => x * 2);

Difference between map method and filter