Codectionary / Developer documentation / JavaScript

map()

map() creates a new array by applying a transformation function to every element of the original array, without modifying it. The new array always has the same length as the original. It is one of the most fundamental tools for transforming data in JavaScript.

Syntax

arr.map(item => transformedItem)

Examples

Basic Transformation

Transforming each element of an array.

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

const squared = numbers.map(n => n ** 2);
console.log(squared); // [1, 4, 9, 16, 25]

Transforming Objects

Extracting or reshaping data from an array of objects.

const users = [
  { firstName: "Alice", lastName: "Smith" },
  { firstName: "Bob", lastName: "Jones" }
];

const fullNames = users.map(u => `${u.firstName} ${u.lastName}`);
console.log(fullNames); // ["Alice Smith", "Bob Jones"]

// Creating new shaped objects
const summaries = users.map(u => ({ name: u.firstName, initial: u.lastName[0] }));
console.log(summaries); // [{ name: "Alice", initial: "S" }, { name: "Bob", initial: "J" }]

map() with Index

Using the optional index parameter passed to the callback.

const items = ["apple", "banana", "cherry"];

const numbered = items.map((item, index) => `${index + 1}. ${item}`);
console.log(numbered);
// ["1. apple", "2. banana", "3. cherry"]

Best practices

  • Use map() only when you need the resulting array - if you just need to run side effects for each item, use forEach() instead
  • Remember map() always returns a new array of the same length, one output for every input - use filter() first if you need to remove elements too
  • Keep the mapping function pure (no side effects) for predictable, easy-to-reason-about code
  • Wrap object literal returns in parentheses when using arrow functions: item => ({ key: value })

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation