The map() method creates a new array by applying a provided function (callbackFn) to each element of the original array. It’s perfect for transforming data without modifying the original array.
Syntax
array.map(callbackFn, thisArg)
-
callbackFn: A function that runs on each array element, with the following arguments:
- element: Current element.
- index: Current index.
- array: The array being traversed.
- thisArg (optional): A value to use as this in the callback function.
Key Features
- Returns a New Array: The original array remains unchanged.
- Skips Empty Slots: Callback is not called for unassigned elements in sparse arrays.
- Generic Usage: Works with array-like objects (e.g., NodeLists).
Examples
1. Basic Example: Transform Numbers
const numbers = [1, 4, 9]; const roots = numbers.map((num) => Math.sqrt(num)); console.log(roots); // [1, 2, 3]
2. Reformat Objects
const kvArray = [ { key: 1, value: 10 }, { key: 2, value: 20 }, ]; const reformatted = kvArray.map(({ key, value }) => ({ [key]: value })); console.log(reformatted); // [{ 1: 10 }, { 2: 20 }]
3. Using parseInt with map
// Common mistake: console.log(["1", "2", "3"].map(parseInt)); // [1, NaN, NaN] // Correct approach: console.log(["1", "2", "3"].map((str) => parseInt(str, 10))); // [1, 2, 3] // Alternative: console.log(["1", "2", "3"].map(Number)); // [1, 2, 3]
4. Avoid Undefined Results
Returning nothing from the callback leads to undefined in the new array:
const numbers = [1, 2, 3, 4]; const result = numbers.map((num, index) => (index <p>Use filter() or flatMap() to remove undesired elements.</p> <h4> 5. Side Effects (Anti-Pattern) </h4> <p>Avoid using map() for operations with side effects, like updating variables:<br> </p> <pre class="brush:php;toolbar:false">const cart = [5, 15, 25]; let total = 0; // Avoid this: const withTax = cart.map((cost) => { total += cost; return cost * 1.2; }); // Instead, use separate methods: const total = cart.reduce((sum, cost) => sum + cost, 0); const withTax = cart.map((cost) => cost * 1.2);
6. Accessing Other Array Elements
The third argument (array) allows accessing neighbors during transformations:
const numbers = [3, -1, 1, 4]; const averaged = numbers.map((num, idx, arr) => { const prev = arr[idx - 1] || 0; const next = arr[idx + 1] || 0; return (prev + num + next) / 3; }); console.log(averaged);
Common Use Cases
- Transform Data: Apply a function to each element.
- Reformat Objects: Change the structure of data.
- Map NodeLists: Transform DOM elements like NodeList into arrays:
const elems = document.querySelectorAll("option:checked"); const values = Array.from(elems).map(({ value }) => value);
When to Avoid map()
- No Return Value Needed: Use forEach() or for...of instead.
- Mutating Data: Create new objects instead of altering the original ones:
const products = [{ name: "phone" }]; const updated = products.map((p) => ({ ...p, price: 100 }));
Final Tips
- Pure Functions Only: Ensure the callback has no side effects.
- Understand Arguments: Know that map() passes element, index, and array to the callback.
- Avoid Sparse Arrays: Empty slots will remain empty.
Use map() to simplify your code when transforming arrays efficiently!
The above is the detailed content of Understanding the map() Method for JavaScript Arrays: A Simple Guide. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
