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

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Security @ Cisco Blogs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
Cyberwarzone
Cyberwarzone
SecWiki News
SecWiki News
Webroot Blog
Webroot Blog
L
LINUX DO - 最新话题
V
Vulnerabilities – Threatpost
T
Troy Hunt's Blog
Cloudbric
Cloudbric
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
H
Heimdal Security Blog
S
Schneier on Security
NISL@THU
NISL@THU
The Hacker News
The Hacker News
Attack and Defense Labs
Attack and Defense Labs
A
Arctic Wolf
V2EX - 技术
V2EX - 技术
Security Latest
Security Latest
AWS News Blog
AWS News Blog
Scott Helme
Scott Helme
W
WeLiveSecurity
S
Secure Thoughts
Y
Y Combinator Blog
GbyAI
GbyAI
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - Franky
量子位
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
K
Kaspersky official blog
P
Privacy & Cybersecurity Law Blog
T
Tenable Blog
The GitHub Blog
The GitHub Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
J
Java Code Geeks
Vercel News
Vercel News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Schneier on Security
Schneier on Security
云风的 BLOG
云风的 BLOG
小众软件
小众软件
Engineering at Meta
Engineering at Meta
宝玉的分享
宝玉的分享
C
CERT Recently Published Vulnerability Notes
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Palo Alto Networks Blog

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 Set Up Time Synchronization on Ubuntu How To Use Struct Tags in Go apt-key Deprecation: Add Repositories with GPG on Ubuntu Linux ps Command: 20 Real-World Examples Python struct.pack and struct.unpack for Binary Data Deadlock in Java: Examples, Detection, and Prevention How To Use Find and Locate to Search for Files on Linux Structured Resume Skill Extraction Using Mistral-7B Inference How to Use the Python Main Function How to Set Up NemoClaw on a DigitalOcean Droplet with 1-Click Build an End-to-End RAG Pipeline for LLM Applications From Single to Multi-Agent Systems: Key Infrastructure Needs Back Up Data to Object Storage Using Restic How to Generate Videos with LTX-2.3 on DigitalOcean GPU Droplets How To Install LAMP Stack (Apache, MySQL, PHP) on Ubuntu How to Download Files with cURL How To Use Variadic Functions in Go Generate UUIDs with uuidgen on Linux How To Use EJS to Template Your Node Application How to Install Node.js on Ubuntu (Step-by-Step Guide) MongoDB Indexes: Improve Query Performance with Node.js LLM Tool Calling with DigitalOcean AI Platform and Databases What are Text Diffusion Models? - An Overview Crafting a Game from Scratch with GPT-5.4 Building Long-Term Memory in AI Agents with LangGraph and Mem0 How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 20.04 Build a GraphQL API in Go to Upload Files to Spaces How To Lint and Format Code with ESLint in Visual Studio Code Train YOLO26 for Retail Object Detection on DigitalOcean GPUs How To Work with JSON in MySQL Building a Scalable App with MongoDB Using DigitalOcean's MCP Server How to Create an SSH Key in Linux: Easy Step-by-Step Guide Measure MySQL Query Performance with mysqlslap How To Use *args and **kwargs in Python 3 Nemotron 3 helped me find the perfect dish rack? A2A vs MCP - How These AI Agent Protocols Actually Differ How To Install and Manage Supervisor Docker Container Images with Watchtower on Ubuntu Getting Started with Qwen3.5 Vision-Language Models How To Create a New Sudo-Enabled User on Ubuntu How to Use Ansible to Install and Set Up Docker on Ubuntu How To Enable Remote Desktop Protocol Using xrdp on Ubuntu 22.04 How To Convert a String to a List in Python How To Check If a String Contains Another String in Python How to Read a Properties File in Python Python Command Line Arguments: sys.argv, argparse, getopt Mastering Grep command in Linux/Unix: A Beginner's Tutorial Understanding Python Data Types How to Implement a Stack in C With Code Examples Python os.system() vs subprocess: Run System Commands How To Install and Use Docker Compose on Ubuntu How to Add and Delete Users on Ubuntu How To Order Query Results in Laravel Eloquent How To Define and Use Handlers in Ansible Playbooks How To Install and Use SQLite on Ubuntu How To Install and Use Homebrew on macOS How To Manage DateTime with Carbon in Laravel and PHP How To Install Git on Ubuntu How To Install and Secure Redis on Ubuntu How To Build and Install Go Programs on Linux Using ldflags to Set Version Information for Go Applications How To Build a Node.js Application with Docker How To Add JavaScript to HTML How To Reset Your MySQL or MariaDB Root Password How To Add Images in Markdown How To Set Up a Production Elasticsearch Cluster with Ansible How To Set Up a Firewall Using firewalld on CentOS Understanding Systemd Units and Unit Files How To Set Up Replication in MySQL How To Use the .htaccess File
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.