惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
爱范儿
爱范儿
罗磊的独立博客
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
U
Unit 42
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
博客园 - 三生石上(FineUI控件)
T
Tailwind CSS Blog
H
Help Net Security
博客园_首页
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
人人都是产品经理
人人都是产品经理

DigitalOcean Community Tutorials

Mastering grep with Regular Expressions for Efficient Text Search It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go
How to Use the JavaScript .map() Method
Anish Singh Walia · 2026-03-11 · via DigitalOcean Community Tutorials

Introduction

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:

  • The .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.
  • Developers commonly use .map() to transform data, such as modifying numbers, extracting object properties, or reshaping datasets.
  • In JavaScript frameworks like React, .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.
  • Array methods like .map(), .filter(), and .reduce() can be chained together to build clear and expressive data transformation pipelines.
  • Use .map() instead of .forEach() when you need to return a new array of transformed values rather than simply performing side effects.

Prerequisites

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.

How to Call a JavaScript Function for Each Item in an Array

.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.

How to Convert a JavaScript String to an Array

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.

How to Render Lists in JavaScript Libraries

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.

How to Reformat JavaScript Array Objects

.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.

Comparing 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.

Chaining Array Methods

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:

Output

24

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.

Performance and Readability Notes

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.

When to Use .map()

Use .map() when you want to:

  • Transform each element in an array
  • Create a new array based on the original array
  • Apply the same operation to every element
  • Chain multiple array operations together

When to Use .forEach()

Use .forEach() when you want to:

  • Run a function for each element in an array
  • Perform side effects, such as logging values
  • Update variables outside the loop
  • Execute operations that do not require returning a new array

Performance Considerations

Although .map() is convenient, there are a few performance considerations to keep in mind:

  • .map() always creates a new array, which requires additional memory.
  • For extremely large datasets, this additional allocation may have a small performance impact.
  • Traditional loops can sometimes offer slightly better performance in highly optimized or performance-critical code paths.

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.

Common Mistakes When Using .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.

Forgetting to Return a Value

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);

Using .map() When You Do Not Need the Returned Array

Another 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);
});

Modifying the Original Array Inside .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);

Forgetting That .map() Always Returns a New Array

Some 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.

FAQs

1. What does .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.

2. Does .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.

3. What is the difference between .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.

4. Can I use .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.

5. When should I use .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.

Conclusion

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:

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.