JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

What’s the difference between map() and forEach() when looping through arrays?

Asked on Oct 07, 2025

Answer

The "map()" and "forEach()" methods both iterate over arrays, but they serve different purposes: "map()" transforms each element and returns a new array, while "forEach()" executes a function for each element without returning a new array.
// Using map()
        const numbers = [1, 2, 3];
        const doubled = numbers.map(num => num * 2);
        console.log(doubled); // Output: [2, 4, 6]

        // Using forEach()
        const numbers = [1, 2, 3];
        numbers.forEach(num => console.log(num * 2));
        // Output: 2
        // Output: 4
        // Output: 6
Additional Comment:
  • "map()" creates a new array with the results of calling a provided function on every element.
  • "forEach()" executes a provided function once for each array element but does not return a new array.
  • Use "map()" when you need to transform data and use "forEach()" for side effects like logging or updating external variables.
✅ Answered with JavaScript best practices.
← Back to All Questions