Concept of the map()
Function
The map()
function applies a given callback function to each element of an array and returns a new array.
The original array remains unchanged during this process.
The callback function passed to the map()
function transforms each element and returns a new array with these transformed values.
This process is called "mapping", which is why the function is named map()
— it maps original values to new ones.
Mapping refers to the process of associating one value with another.
This concept is used in various fields such as mathematics, computer science, and geographic information systems (GIS).
Why Use the map()
Function?
The map()
function is used to transform each element in an existing array according to a specific rule or logic defined in the callback function,
and then creates a new array composed of the transformed elements.
This function is commonly used in scenarios such as:
- Creating a new array of squared values from a number array
- Converting all strings in an array to lowercase
- Extracting specific properties from an array of objects
- Transforming an array into UI components (e.g., rendering JSX in React)
Simple Example to Understand the Concept
Let's explain with a simple example. The following example demonstrates how to use the map()
function to create a new array by doubling each number in a numeric array.
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2; // Returns a new mapped array
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
// The original array remains unchanged.
console.log(numbers); // Output: [1, 2, 3, 4, 5]
map()
can be understood as follows:
/* The map() function is
used to transform each element of an array. */
// In the following example, the goal is to convert all lowercase letters to uppercase.
[a, b, c, d].map(lowercase → uppercase) 👉 [A, B, C, D]
The map()
function iterates over each element and collects the values returned by the callback function, creating a new (mapped) array. Therefore, the callback function must return the transformed or processed result for each corresponding element.
Now, let's take a closer look at how to use the map()
function.
Syntax
arr.map(function(currentValue[, index[, array]]) {
// Logic to transform (map) each element: must return the transformed result
}[, thisArg]);
arr
is the array to which the map()
function is applied.
Parameters
The map()
function takes two parameters:
function (required) |
The callback function applied to each element of the array arr .It accepts up to three arguments:
|
---|---|
thisArg (optional) |
An object to use as this when executing the callback function.This parameter is optional and rarely needed. |
Callback Function Syntax
Here are the common ways to write the callback function for map()
:
// Arrow function with only current value:
map((element) => { /* … */ })
// Arrow function with current value and index:
map((element[, index]) => { /* … */ })
// Arrow function with current value, index, and original array:
map((element[, index[, array]]) => { /* … */ })
// Using a named callback function:
map(callbackFn)
// or with thisArg:
map(callbackFn[, thisArg])
// Inline anonymous function:
arr.map(function(element) { /* ... */ })
arr.map(function(element, index) { /* ... */ })
arr.map(function(element, index, array) { /* ... */ }, thisArg)
How the Callback Works
The map()
function calls the callback once for each element in the array arr in order.
It collects the return values of the callback and creates a new array from them.
Importantly, the original array is not modified during this process.
Return value
Returns a new array containing the results of applying the callback function to each element of the original array.
Difference Between map()
and forEach()
The map()
and forEach()
methods both iterate over elements in an array.
However, the key difference is that map()
applies a callback function to each element and returns a new array with the transformed values, while forEach()
simply executes the callback on each element without returning a new array.
Note:
The forEach()
method is primarily used when you want to perform side effects (like logging or updating an external variable) for each element in the array. It runs the provided callback function once for each element in order, but it does not return a new array.
Here is an example that highlights the difference between map()
and forEach()
:
const numbers = [1, 2, 3, 4, 5];
// Using map()
const squaredNumbersMap = numbers.map(function(number) {
return number * number;
});
console.log("Using map():", squaredNumbersMap);
// Output: Using map(): [1, 4, 9, 16, 25]
// Using forEach()
const squaredNumbersForEach = [];
numbers.forEach(function(number) {
squaredNumbersForEach.push(number * number);
});
console.log("Using forEach():", squaredNumbersForEach);
// Output: Using forEach(): [1, 4, 9, 16, 25]
In the example above, map()
creates a new array by applying the square operation to each element and collecting the results. In contrast, forEach()
performs the same operation, but the results must be manually pushed into a new array since forEach()
does not return anything.
This illustrates the fundamental difference in usage:
- Use
map()
when you need to transform data and create a new array. - Use
forEach()
when you want to perform an operation on each item without returning a new array.
Various Examples of Using map()
Let’s explore how the map()
function works through various examples.
A Simple Example Showing the Function in Action
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(function(number) {
return number * number;
});
console.log(squaredNumbers);
// Output: [1, 4, 9, 16, 25]
Converting Array Elements to Lowercase
Working with arrays of strings is very common.
In this example, map()
is used to convert all the elements of a string array to lowercase and return a new array. The original array remains unchanged.
const fruits = ["Apple", "Banana", "Cherry"];
const lowercaseFruits = fruits.map(function(fruit) {
return fruit.toLowerCase(); // Convert each string to lowercase
});
console.log(lowercaseFruits);
// Output: ['apple', 'banana', 'cherry']
Note:
The toLowerCase()
method converts a string to its lowercase equivalent.
When Array Elements Are Objects
You can also use map()
to extract specific values from an array of objects.
For example, if you want to extract only the names from an array of user objects:
const users = [
{id: 1, name: "Alice"},
{id: 2, name: "Bob"},
{id: 3, name: "Charlie"}
];
const names = users.map(function(user) {
return user.name;
});
console.log(names);
// Output: ['Alice', 'Bob', 'Charlie']
Replacing Values Based on a Condition
You can apply conditional logic to modify each array element before returning a new array.
In this example, even numbers are replaced with the string "Even"
, and odd numbers with "Odd"
:
const numbers = [1, 2, 3, 4, 5];
const modifiedNumbers = numbers.map(function(number) {
if (number % 2 === 0) {
return "Even";
} else {
return "Odd";
}
});
console.log(modifiedNumbers);
// Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
Browser compatibility
method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
map()
|
1 | 12 | 1.5 | 3 |
Specifications
Specification | |
---|---|
map()
|
ECMAScript Language Specification #sec-array.prototype.map |