Skip to main content
0 reactions

How to Change Every Item in an Array with map() in JavaScript

Card titled map() in JavaScript, labelled JavaScript basics, with four ticked lines: the array 10, 20, 30, map price times 2, the result 20, 40, 60, and the old array unchanged.
How to Change Every Item in an Array with map() in JavaScript

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

SyntaxJavaScript
const newArray = array.map((item) => newValue);
  • array: the array to go through.
  • (item) => newValue: a function that map() 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

The Example

Three prices, doubled with map(), in a file named map.js.

Step 1: Write the Code

map.jsJavaScript
const prices = [10, 20, 30];
const doubled = prices.map((price) => price * 2);

console.log(doubled);
console.log(prices);

Step 2: Run It

TerminalBash
node map.js
OutputPlain text
[ 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

MistakeWhat happensDo 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

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments