map() runs a function on every item of an array and collects what the function gives back into a new array. Use it to change every item the same way, such as doubling every price.
Every command and output on this page is real, run with Node.js 26.13.1 on macOS.
Syntax
const newArray = array.map((item) => newValue);
array: the array to go through.(item) => newValue: a function thatmap()calls once for each item, with that item. What it gives back becomes the item in the new array.newArray: the new array, with as many items as the old one.
See Array.prototype.map() (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
The Example
Three prices, doubled with map(), in a file named map.js.
Step 1: Write the Code
const prices = [10, 20, 30];
const doubled = prices.map((price) => price * 2);
console.log(doubled);
console.log(prices);
Step 2: Run It
node map.js
[ 20, 40, 60 ]
[ 10, 20, 30 ]
The first line is the new array, every price doubled. The second shows that prices itself didn’t change: map() always makes a new array.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Braces with no return in the function: (price) => { price * 2; } | Every item of the new array is undefined: [ undefined, undefined, undefined ] | Write (price) => price * 2, or return inside the braces |
FAQ
Does map() change the original array?
No. It gives back a new array and leaves the old one as it was, as the second line of the output shows.
Can the new array hold a different kind of value?
Yes. The function can give back anything, such as a string for each number, and the new array holds those.
Conclusion
array.map((item) => newValue) gives you a new array with every item changed by your function. Make sure the function gives a value back.
Additional Resources
- Array.prototype.map() (opens in a new tab) (MDN)
- Arrow function expressions (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments