map

Create a new array by transforming every item.

Syntaxconst result = arr.map(item => ...)

map() creates a new array by running a function on each item and collecting the results. The original array is unchanged.

When to use it

Reach for map() whenever you want to transform a list into a new list of the same length.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Transform an array of price numbers by applying a tax rate to each, producing a new prices array.
  • Convert an array of user objects into an array of display names for a dropdown menu.
  • Map a list of image filenames to full CDN URLs before rendering an image gallery.

More examples

Apply a calculation to each element

Maps each price to a tax-inclusive value, returning a new array without mutating the original.

Example · js
const prices = [10, 25, 50];
const withTax = prices.map(p => p * 1.08);
console.log(withTax); // [10.8, 27, 54]

Extract a property from objects

Plucks the name property from each user object to produce a plain array of strings.

Example · js
const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" }
];
const names = users.map(u => u.name);
console.log(names); // ["Alice", "Bob"]

Transform to HTML strings

Maps each tag string to an HTML span element string, then joins them into a single HTML block.

Example · js
const tags = ["javascript", "css", "html"];
const chips = tags.map(t => `<span class="chip">${t}</span>`);
document.getElementById("tags").innerHTML = chips.join("");

Discussion

  • Be the first to comment on this lesson.
map — JavaScript | SoundsCode