Interview Q&A / JavaScript

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the difference between map and forEach?

SHORT ANSWER

map returns a new array built from your callback's return values. forEach returns undefined and is only for side effects like logging. Use map to transform data and forEach to do something with each item.

Explain it simply

Imagine a teacher checking answer sheets. forEach is like the teacher walking through the class and ticking each sheet: something happens to each paper but she hands nothing back. map is like a teacher who returns a new pile of marks, one result per sheet.

Both call your function once per element with (item, index, array). The difference is the return value: map collects what your callback returns into a new array of the same length; forEach throws it away and returns undefined.

That is why chaining works on map (.map().filter()) but not on forEach.

Example

js
const fees = [100, 200, 300];

const withGst = fees.map((f) => f * 1.18);
console.log(withGst);                  // Output: [118,236,354]

const result = fees.forEach((f) => f * 2);
console.log(String(result));           // Output: undefined

fees.forEach((f) => console.log("paid " + f));
// Output: paid 100
// Output: paid 200
// Output: paid 300

What to say in the interview

"map transforms each element and returns a new array of the same length, leaving the original untouched. forEach just runs a side effect and returns undefined. If I am not using the returned array, I use forEach or a for...of loop instead of map."

Common mistakes

  • Using map only for side effects and ignoring the result.
  • Trying to break out of forEach with break. It cannot be stopped early.

#javascript#arrays

Related questions

Practise more JavaScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open JavaScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.