Menu
Coddy logo textTech

ForEach And Map Are Same?

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 56 of 65.

While forEach() and map() are both array methods used for iteration, they serve different purposes and have distinct behaviors:

forEach():

  • Executes a provided function once for each array element.
  • Does not create a new array.
  • Returns undefined.
  • Cannot be chained with other array methods.

map():

  • Creates a new array with the results of calling a provided function on every element in the array.
  • Returns a new array of the same length as the original.
  • Can be chained with other array methods.

Example:

const numbers = [1, 2, 3, 4];

// forEach
numbers.forEach(num => console.log(num * 2));
// Logs: 2, 4, 6, 8
// Returns: undefined
// map
const doubled = numbers.map(num => num * 2);
console.log(doubled);
// Output: [2, 4, 6, 8]
// Returns: A new array [2, 4, 6, 8]

Use forEach() when you want to perform an operation on each element without creating a new array. Use map() when you want to transform each element and create a new array with the results.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

Cheat sheet

While forEach() and map() are both array methods used for iteration, they serve different purposes:

forEach():

  • Executes a function once for each array element
  • Does not create a new array
  • Returns undefined
  • Cannot be chained with other array methods

map():

  • Creates a new array with the results of calling a function on every element
  • Returns a new array of the same length as the original
  • Can be chained with other array methods
const numbers = [1, 2, 3, 4];

// forEach - performs operation, returns undefined
numbers.forEach(num => console.log(num * 2));

// map - transforms elements, returns new array
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]

Use forEach() for operations without creating a new array. Use map() to transform elements and create a new array.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow