What is the difference between map and forEach in JavaScript?
Written by Jatin Thacker, Automation Architect · Updated
map() calls your function on every element and returns a new array of the results. forEach() calls your function on every element and always returns undefined, so it is only for side effects.This answer is one piece of Chapter 4: Arrays and Objects.
Both walk an array and call a function for each element. The difference is what you get back, and that decides which one you reach for.
Use map() when you want a new list built from the old one. In the example, prices.map((p) => Math.round(p * 1.18)) returns the three prices with GST added, and prices itself is unchanged. That is the shape of most test-data work: turn product rows into expected strings, or order objects into ids.
Use forEach() when you want something to happen for each element and need nothing back, such as adding to a running total. The example shows that forEach() returns undefined, so code that stores its result has stored nothing.
One trap matters more than the rest in test code. forEach() does not wait for promises. Give it an async callback and it starts every call, ignores the promises they return, and moves on before any of them finish. For awaited steps, use a for...of loop with await, or await Promise.all(items.map(...)) when the steps can run together.
const prices = [4290, 6490, 11900];
const withGst = prices.map((p) => Math.round(p * 1.18));
console.log('map returns:', withGst);
const fromForEach = prices.forEach((p) => Math.round(p * 1.18));
console.log('forEach returns:', fromForEach);
let total = 0;
prices.forEach((p) => { total += p; });
console.log('forEach used for a side effect:', total);
console.log('original unchanged:', prices);map returns: [ 5062, 7658, 14042 ] forEach returns: undefined forEach used for a side effect: 22680 original unchanged: [ 4290, 6490, 11900 ]
result after const result = [4290, 6490].forEach((p) => p * 2)?Practised in the full course: the drill forEach does not wait.
See the chapterRelated questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free