By Anish Singh Walia and mkurup

From the classic for loop to the forEach() method, there are many ways to iterate through data sets in JavaScript. One of the most popular options is the .map() method. The .map() method creates a new array by calling a function on every element of the original array and collecting the returned values. The .map() method is non-mutating, meaning it returns a new array without modifying the original array. This differs from mutating methods, which directly change the array they are called on.
This method has many practical uses when working with arrays and transforming data. In this tutorial, you’ll look at four noteworthy uses of .map() in JavaScript: calling a function for each array element, converting strings to arrays, rendering lists in JavaScript libraries, and reformatting array objects.
Deploy your frontend applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.
Key Takeaways:
.map() method iterates over an array and returns a new array containing the values produced by a callback function..map() is a non-mutating method, meaning it does not modify the original array..map() to transform data, such as modifying numbers, extracting object properties, or reshaping datasets..map() is often used to render lists of UI elements from arrays of data..map() works best when you need to apply the same transformation to every element in an array..map(), .filter(), and .reduce() can be chained together to build clear and expressive data transformation pipelines..map() instead of .forEach() when you need to return a new array of transformed values rather than simply performing side effects.This tutorial does not require any coding, but if you are interested in following along with the examples, you can either use the Node.js REPL or browser developer tools.
To install Node.js locally, you can follow the steps at How to Install Node.js and Create a Local Development Environment.
You can use Chrome DevTools by downloading and installing the latest version of Google Chrome.
.map() accepts a callback function as one of its arguments. The callback commonly receives the current element being processed as its first parameter, which allows you to work with each value in the array. Using this parameter, you can transform each item in the array and return the result as part of a new array.
Here’s an example:
const sweetArray = [2, 3, 4, 5, 35];
const sweeterArray = sweetArray.map(sweetItem => {
return sweetItem * 2;
});
console.log(sweeterArray);
This output is logged to the console:
Output[ 4, 6, 8, 10, 70 ]
You can simplify this example to make it a bit cleaner:
// Create a function to use.
const makeSweeter = sweetItem => sweetItem * 2;
// We have an array.
const sweetArray = [2, 3, 4, 5, 35];
// Call the function we made; this is more readable.
const sweeterArray = sweetArray.map(makeSweeter);
console.log(sweeterArray);
The same output is logged to the console:
Output[ 4, 6, 8, 10, 70 ]
Using code like sweetArray.map(makeSweeter) can make your intent a bit clearer.
The .map() method belongs to the array prototype. In this section, you will use it to convert a string to an array by using the special .call() method. You are not redefining .map() to work for strings. Instead, you are borrowing the existing array method and running it with a string as the context.
JavaScript has both objects and primitive values such as strings and numbers. Although strings are primitive values, they behave like array-like objects because their characters can be accessed by index and they have a length property.
Methods in JavaScript are functions attached to objects. The .call() method allows you to invoke a function while explicitly setting the value of this. By using .call(), you can run the .map() method with a string as its context.
.call() accepts the context to use as its first argument, followed by any parameters expected by the original function.
Here’s an example:
const name = "Sammy";
const map = Array.prototype.map;
const newName = map.call(name, eachLetter => {
return `${eachLetter}a`;
});
console.log(newName);
This output is logged to the console:
Output[ "Sa", "aa", "ma", "ma", "ya" ]
Here, you used the context of .map() on a string and passed the callback function that .map() expects.
This works because strings are array-like values with indexed characters. Using .call() allows the .map() method to iterate over those characters and return a new array with the transformed results.
This works similarly to the .split() method on a string, except that each individual character can be modified before being returned in an array.
JavaScript libraries like React commonly use .map() to render items in a list. In React applications, .map() is often used inside JSX expressions to generate a list of elements from an array of data.
Here’s an example of a React component:
import React from "react";
import { createRoot } from "react-dom/client";
const names = ["whale", "squid", "turtle", "coral", "starfish"];
const NamesList = () => (
<div>
<ul>{names.map(name => <li key={name}>{name}</li>)}</ul>
</div>
);
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<NamesList />);
This is a stateless React component that renders a div containing a list. The individual list items are generated using .map() to iterate over the names array and create a <li> element for each item.
The component is rendered using React on the DOM element with the id of root.
.map() can also be used to iterate over an array of objects and transform the contents of each object. Similar to other uses of .map(), the method returns a new array containing the values returned from the callback function.
Here’s an example:
const myUsers = [
{ name: 'shark', likes: 'ocean' },
{ name: 'turtle', likes: 'pond' },
{ name: 'otter', likes: 'fish biscuits' },
];
const usersByLikes = myUsers.map(item => {
const container = {};
container[item.name] = item.likes;
container.age = item.name.length * 10;
return container;
});
console.log(usersByLikes);
This output is logged to the console:
Output[
{ shark: "ocean", age: 50 },
{ turtle: "pond", age: 60 },
{ otter: "fish biscuits", age: 50 }
]
In this example, .map() iterates over an array of objects and returns a new array with reformatted objects. The callback function creates a new object for each entry and assigns new properties using bracket and dot notation.
This approach can be useful when transforming or restructuring data before displaying it in a user interface or sending it to another part of an application.
map(), forEach(), and filter()JavaScript provides several array iteration methods that are useful for working with collections of data. While .map() is commonly used to transform array values, methods such as .forEach() and .filter() serve different purposes.
Understanding when to use each method can help you write clearer and more maintainable code.
For example, .map() transforms values and returns a new array:
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled);
This produces the following output:
Output[ 2, 4, 6 ]
In contrast, .forEach() does not return a new array and is often used for side effects:
numbers.forEach(num => {
console.log(num);
});
Meanwhile, .filter() returns a new array containing only elements that satisfy a condition:
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);
This produces the following output:
Output[ 2 ]
Here’s a quick summary table:
| Method | Purpose | Returns a New Array | Typical Use Case |
|---|---|---|---|
.map() |
Transforms every element in an array | Yes | Converting or modifying values |
.forEach() |
Executes a function for each element | No | Performing side effects such as logging or updating variables |
.filter() |
Selects elements that match a condition | Yes | Creating a subset of an array |
In general, use .map() when you want to transform every element in an array, .filter() when you want to select certain elements, and .forEach() when you simply want to run a function for each item without creating a new array.
Array methods such as .map(), .filter(), and .reduce() can be chained together to perform multiple transformations in a single sequence. Because methods like .map() and .filter() return new arrays, you can immediately call the next array method on the returned value.
Chaining can make your code more concise and easier to read because each step expresses a single, focused operation. It can also reduce the need for temporary variables when your transformation pipeline is short and the intent is clear.
The order of chained methods matters because each method receives the output of the previous step. As a general rule, it is common to put selection methods like .filter() earlier so that later steps process fewer elements.
It is also important to understand that .reduce() is usually the final method in a chain, because it returns a single value (such as a number, string, or object) rather than a new array.
For example, you might first filter an array and then transform the remaining values:
const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers
.filter(num => num % 2 === 0)
.map(num => num * 2);
console.log(result);
This produces the following output:
Output[ 4, 8, 12 ]
In this example, .filter() first creates a new array containing only the even numbers. The resulting array is then passed to .map(), which multiplies each value by two.
You can also chain into .reduce() when you want to aggregate the transformed values into a single result. For example, you can filter and map the values, and then sum them:
const numbers = [1, 2, 3, 4, 5, 6];
const total = numbers
.filter(num => num % 2 === 0)
.map(num => num * 2)
.reduce((sum, num) => sum + num, 0);
console.log(total);
This produces the following output:
Output24
Chaining array methods is commonly used in modern JavaScript to process data in a clear and declarative way. Instead of writing multiple loops, you can combine small operations that transform data step by step.
When you are writing chained code, try to keep your callbacks free of side effects and have them return values consistently. If your chain becomes long or hard to follow, you can make the code easier to debug by assigning intermediate results to well-named variables, or you can switch to a loop if you need maximum performance on large datasets.
In most real-world applications, the performance differences between .map(), .forEach(), and traditional looping constructs such as for or while loops are generally small. Modern JavaScript engines are heavily optimized to execute common iteration patterns efficiently. Because of these optimizations, choosing between these approaches is usually more about code clarity and intent than raw performance.
Methods like .map() are particularly useful because they clearly communicate that a new array is being created from an existing one. When another developer reads code that uses .map(), they can quickly understand that the goal is to transform each element of the original array and produce a new array containing the transformed values.
For example, the following code clearly indicates that each number in the array is being doubled:
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
Using .map() makes the transformation explicit and avoids manually managing the iteration process.
A traditional for loop can achieve the same result, but it typically requires more boilerplate code:
const numbers = [1, 2, 3];
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
doubled.push(numbers[i] * 2);
}
Both examples produce the same result, but the .map() version is shorter and focuses directly on the transformation instead of the mechanics of looping.
.map()Use .map() when you want to:
.forEach()Use .forEach() when you want to:
Although .map() is convenient, there are a few performance considerations to keep in mind:
.map() always creates a new array, which requires additional memory.However, in most applications these differences are negligible. Developers typically prioritize readability and maintainability over minor performance gains.
In general, .map() is the preferred approach when transforming array data. Its concise syntax and clear intent make code easier to understand and maintain, especially in modern JavaScript applications.
.map()Although .map() is a straightforward method, beginners often make a few common mistakes when using it. Understanding these mistakes can help you avoid unexpected results and write clearer code.
One of the most common mistakes when using .map() is forgetting to return a value from the callback function. The value returned from the callback becomes the corresponding element in the new array.
If the callback does not return anything, .map() will insert undefined for that element.
For example:
const numbers = [1, 2, 3];
const doubled = numbers.map(num => {
num * 2;
});
console.log(doubled);
This produces the following output:
Output[ undefined, undefined, undefined ]
This happens because the callback does not explicitly return a value. To fix this issue, return the transformed value:
const doubled = numbers.map(num => {
return num * 2;
});
You can also use an implicit return with arrow functions:
const doubled = numbers.map(num => num * 2);
.map() When You Do Not Need the Returned ArrayAnother common mistake is using .map() when you are not using the array that it returns. Because .map() always creates a new array, it should be used when you intend to transform data and store the result.
For example, this code uses .map() incorrectly:
const numbers = [1, 2, 3];
numbers.map(num => {
console.log(num);
});
Although this works, the returned array is ignored. In cases like this, .forEach() is usually a better choice:
numbers.forEach(num => {
console.log(num);
});
.map()Another mistake is modifying the original array while using .map(). The purpose of .map() is to create a new array based on the values of an existing one, not to change the original data.
For example:
const numbers = [1, 2, 3];
const result = numbers.map((num, index, arr) => {
arr[index] = num * 2;
return num * 2;
});
Although this code works, it modifies the original array, which can lead to unexpected behavior in larger applications.
A better approach is to return the transformed value without altering the original array:
const result = numbers.map(num => num * 2);
.map() Always Returns a New ArraySome developers expect .map() to modify the original array. However, .map() always returns a new array and leaves the original array unchanged.
For example:
const numbers = [1, 2, 3];
numbers.map(num => num * 2);
console.log(numbers);
Output:
Output[ 1, 2, 3 ]
To store the transformed values, you must assign the result to a new variable:
const doubled = numbers.map(num => num * 2);
Understanding these common mistakes will help you use .map() more effectively and avoid subtle bugs when working with array data.
.map() do in JavaScript?The .map() method iterates over an array and applies a callback function to each element. The value returned from the callback becomes the corresponding element in a new array that .map() creates and returns. This makes .map() useful for transforming or reformatting data while preserving the original array.
For example, you might use .map() to convert numbers, extract properties from objects, or reshape data before displaying it in a user interface.
.map() change the original array?No, .map() does not change the original array. It is a non-mutating method, meaning it returns a new array containing the transformed values while leaving the original array unchanged.
However, if the callback function explicitly modifies elements of the original array, those changes will still occur. In most cases, .map() is used to create a new transformed array without altering the original data.
.map() and .forEach()?Both .map() and .forEach() iterate over elements in an array and execute a callback function for each item. The key difference is that .map() returns a new array, while .forEach() does not return a value.
Use .map() when you want to transform each element in an array and store the results in a new array. Use .forEach() when you simply want to perform an action for each element, such as logging values, updating variables, or triggering side effects.
.map() on objects?.map() is designed to work with arrays and array-like values, so it cannot be used directly on plain JavaScript objects.
If you need to apply .map() to object data, you can first convert the object’s keys or values into an array using methods such as Object.keys(), Object.values(), or Object.entries(). Once the data is in array form, you can use .map() to transform it.
.map() instead of .filter()?Use .map() when you want to transform every element in an array and produce a new array with the transformed values. For example, you might use .map() to double numbers, extract properties from objects, or convert values into a different format.
Use .filter() when you want to select only certain elements from an array based on a condition. Instead of transforming values, .filter() returns a new array containing only the elements that match the specified criteria.
In this tutorial, you explored several practical uses of the .map() method in JavaScript. You learned how to transform array values, convert strings into arrays, render lists in JavaScript libraries, and reformat arrays of objects.
You also compared .map() with related array methods such as .forEach() and .filter(), learned how array methods can be chained together, and reviewed common mistakes such as forgetting to return a value from the callback function.
Understanding how and when to use .map() can help you write clearer and more expressive JavaScript code. For more such JavaScript-related tutorials, check out the following articles:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer(Team Lead) @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
“With this parameter, you can modify each item in an array and create a new function.”
Shouldn’t this say “create a new array”? I don’t see how .map creates a “new function”.
This infromation is relevant to the content if want to know more about our link
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.