JavaScript Array map() Method with Live Examples
Direct Answer & Overview
The JavaScript Array map() method creates a new array populated with the results of calling a provided callback function on every element in the calling array. It performs immutable data transformation without modifying the original array.
JavaScript Source Code
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(number => number * 2);
console.log(doubled);How does this JavaScript code work?
Array.prototype.map() is a foundational higher-order method in functional JavaScript programming. It iterates through the calling array in ascending index order, invoking the provided transformation function on each element. The return value of each callback invocation is collected into a brand-new array of identical length. Crucially, map() never mutates the original input array, making it ideal for predictable state management in UI libraries like React.
What is the expected terminal output?
Executing this code in JS CodeLab produces the following stdout sequence in the developer console:
[2,4,6,8,10]Common mistakes to avoid
- !Using map() when you don't use the returned array; use forEach() or for...of instead to avoid allocating unnecessary memory.
- !Forgetting to return a value from the callback function, resulting in an array populated with undefined items.
- !Directly mutating item properties inside the callback instead of returning clean shallow copies, causing unintended side effects.
- !Attempting to use break or continue statements inside map(); use standard for loops if early termination is needed.
Frequently Asked Questions
Does Array.prototype.map() mutate the original array?
No. The map() method creates and returns a brand-new array. However, if the array contains objects and you mutate their properties inside the callback, those mutations will affect the original references.
What is the difference between Array map() and forEach()?
The map() method constructs and returns a new transformed array of identical length, whereas forEach() executes side effects for each element and always returns undefined.
What parameters are passed to the map() callback function?
The callback function receives three arguments on every iteration: the current element value, the current index number (0-indexed), and the complete original array being traversed.
How can you run asynchronous operations with Array map()?
When an async callback is passed to map(), it returns an array of pending Promises. You must resolve them collectively using Promise.all(array.map(async ...)).
Comprehensive Tutorial
Want an in-depth understanding of this topic?
Read our complete, interactive tutorial covering memory management, edge cases, and best practices.
Read the full map vs-foreach tutorial →