The JavaScript Array map() method creates a new array by running a callback once for each present element and putting each returned value into the corresponding position. It is useful for transforming data without replacing or editing the source array. You can use it to format values, extract object properties, or build data for a user interface. This guide adds practical patterns and explains when map() is a better fit than forEach(), filter(), or flatMap().
Syntax and Formal Specification
The method signature is map(callbackFn, thisArg).
const prices = [10, 20, 30]; const withTax = prices.map(p => p * 1.15); console.log(withTax); // [11.5, 23, 34.5]
Parameters
-
callbackFn— A function invoked for each element. It receives three arguments:-
element— The current element being processed. -
index— The integer index of the current element. -
array— The array on whichmap()was called.
-
-
thisArg(optional) — A value used asthisinside the callback when the callback is a non-arrow function. Ignored for arrow functions, which lexically bindthis.
Return Value
A new array of the same length as the source array (including holes—see below) where each element is the return value of the callback for that position. If the callback returns undefined, the corresponding element in the new array is undefined.
const arr = [1, 2, 3]; const result = arr.map(x => undefined); console.log(result); // [undefined, undefined, undefined] console.log(result.length); // 3
Immutability and the Transformation Contract
map() does not mutate the array. It returns a new array, leaving the original untouched. This makes map() a fundamental building block for functional and immutable programming styles—React rendering, Redux reducers, and pure data pipelines all rely on map() for element-wise transformation.
const original = [1, 2, 3]; const transformed = original.map(x => x + 1); console.log(original); // [1, 2, 3] console.log(transformed); // [2, 3, 4] console.log(original === transformed); // false (distinct arrays)
Shallow Copy vs Deep Copy
map() creates a shallow copy of the array structure. If the callback returns elements that are objects, those objects are shared by reference between the source and result arrays. This is intentional but requires care in immutability-sensitive contexts:
const users = [{ name: "Alice" }, { name: "Bob" }]; // Shallow transformation: returns same object references const names = users.map(u => u.name); // ["Alice", "Bob"] const shuffled = users.map(u => ({ ...u })); // new objects, shallow copy shuffled[0].name = "Alicia"; console.log(users[0].name); // "Alice" (original untouched) console.log(shuffled[0].name); // "Alicia"
For deep copies of nested structures, use structuredClone() (Node.js 17+, modern browsers):
const deepCopy = users.map(u => structuredClone(u));
Performance Characteristics
map() runs in O(n) time and allocates a new array of length n. For typical array sizes, the cost is dominated by callback invocations and object allocation. Engines such as V8 have specialized optimizations for map() on dense arrays with simple callbacks—they may inline the callback in hot loops and preallocate the result array with the correct size.
const big = new Array(1_000_000).fill(1); const t1 = performance.now(); const doubled = big.map(x => x * 2); console.log(performance.now() - t1); // proportional to n
Callback Overhead
Each element invokes a user-defined function. For hot loops over large arrays, this cost is significant compared to inline operations:
// Faster: manual loop avoids function calls const manual = new Array(big.length); for (let i = 0; i < big.length; i++) manual[i] = big[i] * 2; // Slower: callback invocation per element const viaMap = big.map(x => x * 2);
For most application code, the readability of map() outweighs the micro-optimization. Reserve manual loops for performance-critical sections where profiling shows map() is a bottleneck.
map() with Async Callbacks (Antipattern)
map() does not wait for async callbacks. If the callback returns a Promise, the resulting array is an array of Promises—not resolved values. Use Promise.all() to unwrap them:
const ids = [1, 2, 3]; // Returns array of promises: const promises = ids.map(async id => await fetchUser(id)); // Wait for all to resolve: const users = await Promise.all(promises); // Or use for...of for sequential processing: const usersSequential = []; for (const id of ids) { usersSequential.push(await fetchUser(id)); }
Promise.all() runs the async operations in parallel, while sequential for...of runs them one at a time. Choose based on concurrency needs and rate limits.
Return a value for every element
The callback’s return value becomes the corresponding element in the new array. A concise arrow function returns its expression automatically. When you use a block body with braces, write an explicit return; otherwise the callback returns undefined.
const words = ["map", "makes", "arrays"];
const lengths = words.map(word => {
return word.length;
});
console.log(lengths); // [3, 5, 6]
If the transformation needs several steps, calculate a named value and return it. This keeps the callback understandable and ensures that every input element has a clear output.
const prices = [12, 25, 40];
const pricesWithTax = prices.map(price => {
const tax = price * 0.1;
return price + tax;
});
console.log(pricesWithTax); // [13.2, 27.5, 44]
Transform arrays of objects
A frequent task is converting a list of records into a list of values or display-ready objects. The callback can read multiple properties and return a new shape for each entry.
const users = [
{ id: 1, firstName: "Asha", active: true },
{ id: 2, firstName: "Rafi", active: false }
];
const labels = users.map(user => ({
key: user.id,
text: user.firstName,
status: user.active ? "Active" : "Inactive"
}));
console.log(labels);
// [{ key: 1, text: "Asha", status: "Active" },
// { key: 2, text: "Rafi", status: "Inactive" }]
The new objects are separate from the original records, but any nested objects you place directly into the result remain shared references unless you copy them too. For example, returning { user } keeps the original user object inside the new wrapper.
map() versus forEach() and filter()
Use map() when every input position should produce a corresponding output value. Use forEach() when you want to perform an action for each item and do not need a returned array. Use filter() when you want to keep only the items that pass a test.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(number => number * 2);
const evens = numbers.filter(number => number % 2 === 0);
const logged = [];
numbers.forEach(number => logged.push(number));
console.log(doubled); // [2, 4, 6, 8]
console.log(evens); // [2, 4]
console.log(logged); // [1, 2, 3, 4]
Returning a Boolean from map() creates an array of Booleans; it does not filter the source values. For example, numbers.map(n => n > 2) produces [false, false, true, true]. If that is not the result you want, choose filter() or some() instead.
Working with sparse arrays
map() calls its callback only for indexes that exist in the source array. Empty slots, called holes, are skipped, and the corresponding positions remain holes in the result. This is different from an explicit undefined value, which is a present element and is passed to the callback.
const sparse = [10, , 30];
const result = sparse.map(value => value * 2);
console.log(result); // [20, empty, 60]
console.log(1 in result); // false
If every output position must contain a value, make sure the source array is dense or fill missing positions before mapping. The array’s length stays the same, but a hole does not become an undefined element automatically.
Use flatMap() when each item creates several values
map() always preserves one output position for each visited input position. If a callback returns an array, the result becomes nested. Use flatMap() when one input should produce zero, one, or several values in a single flat result.
const phrases = ["hello world", "learn JavaScript"];
const words = phrases.flatMap(phrase => phrase.split(" "));
console.log(words);
// ["hello", "world", "learn", "JavaScript"]
With map(), this example would return an array of arrays. flatMap() maps each phrase and flattens the returned arrays by one level, which is convenient for splitting, expanding, or omitting results.