What is the big difference between forEach and map?
<p>Here's something I don't understand. The <code>map</code> function, which I just learned about a few days ago, is supposed to be some amazing function that will transform the way I write code if I find uses for it. But I still don't see how it's any different than <code>forEach</code>. The only difference is that the function passed to <code>map</code> replaces the current element with the <code>return</code> value. But <code>forEach</code> can do that too, which means that <code>map</code> is just a less general version of <code>forEach</code>. </p>

<p>Example on MDN: </p>

<pre><code>var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3], numbers is still [1, 4, 9]
</code></pre>

<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map</a></p>

<p>Ok, cool, I guess? </p>

<p>I can do that with <code>forEach</code>:</p>

<pre><code>var numbers = [1, 4, 9];
var roots = numbers.forEach(function(el){el=Math.sqrt(el);});
// roots is now [1, 2, 3], numbers is still [1, 4, 9]
</code></pre>

<p>Other example: </p>

<pre><code>var kvArray = [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}];
var reformattedArray = kvArray.map(function(obj){ 
   var rObj = {};
   rObj[obj.key] = obj.value;
   return rObj;
});
// reformattedArray is now [{1:10}, {2:20}, {3:30}], 
// kvArray is still [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}]
</code></pre>

<p>I can do that with <code>forEach</code> and it looks almost identical.</p>

<p>What's so good about <code>map</code>? What is an example where it works super-well where <code>forEach</code> wouldn't work?</p>