Back
LearnJavaScript From Zeromap & forEach — working with every item

map & forEach — working with every item

2 min read

Loops are fine — but there is a cleaner way

You already know how to walk through an array with a loop. JavaScript also gives you shorter, clearer tools built just for arrays. The first two: forEach and map.

forEach — do something for each item

forEach runs a function once for every item. Use it when you just want to act on each one.

let names = ["Riya", "Sam", "Neha"];

names.forEach((name) => {
  console.log("Hello " + name);
});

No index counting, no length — cleaner than a for loop for simple jobs.

map — turn a list into a new list

This is the one you will use the most. map takes each item, changes it, and gives back a brand new array of the results.

let prices = [100, 200, 300];
let withTax = prices.map((p) => p * 1.18);
console.log(withTax);   // [118, 236, 354]

Read it as: "for each price p, give back p * 1.18". The original prices stays untouched — map never changes the old array, it builds a new one.

How is map different from forEach?

  • forEachdoes something, gives back nothing.
  • maptransforms and gives back a new array.

If you want a new list out, use map. If you just want to perform an action, use forEach.

map = "turn this list into a new list". It is at the heart of how modern JavaScript handles data.

Tip