JavaScript's array methods forEach() and map()

Friday, August 29, 2025

Explain JavaScript’s array methods forEach() and map().

Summary table

FeatureforEach() 🌀map() 🔁
PurposeRun side effects (e.g., log, update external variable).Transform array elements into a new array.
Return valueundefinedA new array of same length.
Mutates array?No (unless you mutate inside callback).No (pure function, unless you mutate inside).
Chainable?❌ No✅ Yes (can chain with .filter(), .reduce()).
PerformanceSimilar (slightly faster since forEach doesn’t build a new array).Slight overhead because it creates a new array.
Use caseLogging, counters, saving data externally.Transforming data (e.g., square numbers, extract fields).

forEach()

array.forEach((element, index, array) => {
  // Do something with element
  // Executes the callback on each element.
  //Does not return a new array → always undefined.
});

map()

const newArray = array.map((element, index, array) => {
  return element * 2;
  //Executes the callback on each element.
  //Returns a new array with transformed values.
  //Original array is unchanged.
});

Example

const array = [1, 2, 3];

// forEach example
const newArrayWithForEach = array.forEach((item) => item * 2);

// map example with a return
const newArrayWithMap = array.map((item) => {
  return item; // If you don't return a value, map will insert 'undefined' instead
});

// map example without a return
const undefinedArrayWithMap = array.map((item) => {
  // no return here → implicit 'undefined'
});

console.log(newArrayWithForEach); // undefined (forEach always returns undefined, not an array)
console.log(newArrayWithMap); // [1, 2, 3]
console.log(undefinedArrayWithMap); // [undefined, undefined, undefined]