Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The voted answer (from Ken Redler) is misleading. </p> <p>A <strong>side effect</strong> in computer science means that a property of a function/method alters a global state <a href="http://en.wikipedia.org/wiki/Side_effect_(computer_science)" rel="nofollow noreferrer" title="side effect wiki">[wiki]</a>. In some narrow sense, this may also include reading from a global state, rather than from arguments. In imperative or OO programing, side effects appear most of the time. And you are probably making use of it without realizing.</p> <p>The significiant difference between <code>forEach</code> and <code>map</code> is that <code>map</code> allocates memory and stores the returning value, while <code>forEach</code> throws it away. See <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18" rel="nofollow noreferrer">emca spec</a> for more information.</p> <p>As for the reason why people say <code>forEach</code> is used when you want a side effect is that the return value of <code>forEach</code> is always <code>undefined</code>. If it has no side effect (does not change global state), then the function is just wasting cpu time. An optimizing compiler will eliminate this code block and replace the it with the final value (<code>undefined</code>). </p> <p>By the way, it should be noted that JavaScript has no restriction on side effects. You can still modify the original array inside <code>map</code>.</p> <pre><code>var a = [1,2,3]; //original var b = a.map( function(x,i){a[i] = 2*x; return x+1} ); console.log("modified=%j\nnew array=%j",a,b); // output: // modified=[2,4,6] // new array=[2,3,4] </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload