Back to all questions

What is the difference between map and forEach in an Array

Devs Hive

Devs Hive

Seen on interview: 3 users

Quite a few interview questions are about array methods. You may be asked which methods you know, for example. And once you finish listing them, one of the follow-up questions might be: "What is the difference between the map and forEach array methods, and when is it better to use each of them?"

In a technical interview, you should say that both iterate over an array, but the difference is that the map method імутабельний and creates a new array based on the original one, while forEach simply iterates over it without returning any result.

Let's look at an example

Say you want to multiply each element of the array and then return the result. With map you get a new array, while with forEach you have to use a closure to store the result.

// Використання map
const numbers = [1, 2, 3, 4];

const squares = numbers.map((n) => n * n);

console.log(squares); // [1, 4, 9, 16]
console.log(numbers); // [1, 2, 3, 4] - оригінал не змінився, так як map імутабельний

// Використання forEach
const numbers = [1, 2, 3, 4];
const squares = [];

numbers.forEach((n) => {
// Використовуємо замкнення, щоб зберігати результат
squares.push(n * n);
});

console.log(squares); // [1, 4, 9, 16]
console.log(numbers); // [1, 2, 3, 4]

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!