JavaScript Array map() method creates a new array by applying a callback function to each element of the original array. It is an essential tool for transforming data in functional programming and is commonly used for manipulating arrays in a concise and readable way.

Pre-requisites to Learn
Syntax
arr.map(callback(element, index, array), thisArg);
Parameters
Parameter | Description |
---|---|
callback (Required) | A function that is executed for each element in the array. |
element (Required) | The current element being processed. |
index (Optional) | The index of the current element being processed. |
array (Optional) | The array map() was called on. |
thisArg (Optional) | A value to use as this when executing the callback function. Defaults to undefined. |
Return Value
The map() method returns a new array containing the results of applying the callback function to each element of the original array. The original array is not modified.
Note: The map() method modifies the original array. It is used to apply transformations to each element of an array.
Examples of JavaScript Array map() Method
Example 1: The map() method applies the doubling function to each element and returns a new array with the transformed values.
let arr = [1, 2, 3, 4]; let doubled = arr.map(num => num * 2); console.log(doubled); // Output: [2, 4, 6, 8]
Example 2: Calculating the length of each string in the array and creates a new array with those lengths.
let arr = ['apple', 'banana', 'cherry']; let lengths = arr.map(fruit => fruit.length); console.log(lengths); // Output: [5, 6, 6]
Example 3: The index parameter allows access to the current element’s position during the iteration.
let arr = [10, 20, 30]; let arrWithIndex = arr.map((num, index) => `Index ${index}: ${num}`); console.log(arrWithIndex); // Output: ['Index 0: 10', 'Index 1: 20', 'Index 2: 30']
Example 4: This example extracts specific properties (name) from an array of objects.
let users = [ { id: 1, name: 'John' }, { id: 2, name: 'Alice' }, { id: 3, name: 'Bob' } ]; let userNames = users.map(user => user.name); console.log(userNames); // Output: ['John', 'Alice', 'Bob']
Example 5: Processing empty slots as undefined, allowing developers to handle them explicitly.
let sparseArr = [1, , 3]; let result = sparseArr.map(num => num || 0); console.log(result); // Output: [1, 0, 3]
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1.5+ |
Safari | 3+ |
Edge | 12+ |
Opera | 9.5+ |
Internet Explorer | 9+ |
Comparison with Other Methods
Method | Purpose |
---|---|
Array.map() Method | Transforms each element and returns a new array. |
Array.forEach() Method | Executes a callback for each element but does not return a new array. |
Array.filter() Method | Returns a new array containing only the elements that satisfy a given condition. |
Array.reduce() Method | Reduces the array to a single value or object based on a callback function. |