Skip to main content
Practice Problems

What is the difference between Map and foreach in Array?

markdown
## Understanding the Difference Between `map` and `forEach` in JavaScript Arrays In a technical interview, it's important to mention that both methods iterate over an array, but the difference is that the `map` method is `immutable` and will create a new array based on the original, while the `forEach` method simply iterates over it without returning any result. ### Example Breakdown To illustrate the difference, let's consider an example where we multiply each element of the array and then return the result. In the case of `map`, you will get a new array, while with `forEach`, you will need to use a closure to store the result. #### Using `map` ```javascript const temperatures = [32, 45, 50, 60]; const increasedTemperatures = temperatures.map((temp) => temp + 10); console.log(increasedTemperatures); // [42, 55, 60, 70] console.log(temperatures); // [32, 45, 50, 60] - original remains unchanged

Using forEach

javascript
const tempArray = [32, 45, 50, 60]; const adjustedTemps = []; tempArray.forEach((temp) => { adjustedTemps.push(temp + 10); }); console.log(adjustedTemps); // [42, 55, 60, 70] console.log(tempArray); // [32, 45, 50, 60]

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems