Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are not creating a new function on each iteration in the second example. There is only one function that keeps getting called over and over. To clarify the point of only a single function being used, consider how would you implement the <code>each</code> method yourselves.</p> <pre><code>Array.prototype.each = function(fn) { for(var i = 0; i &lt; this.length; i++) { // if "this" should refer to the current object, then // use call or apply on the fn object fn(this[i]); } } // prints each value (no new function is being created anywhere) [1, 2, 3].each(function(v) { console.log(v); }); </code></pre> <p>Sure, there is the overhead of calling a function in the first place, but unless you are dealing with massive collections, this is a non-issue in modern browsers.</p> <p>Personally I prefer the second approach for the simple reason that it frees me from worrying about unnecessary details that I shouldn't be concerned about in the first place. Say if we are looping through a collection of employee objects, then index is just an implementation detail and in most cases, if not all, can be abstracted away from the programmer by constructs such as the <code>each</code> method in Prototype, which by the way is now a standard in JavaScript as it has been incorporated into ECMAScript 5th ed under the name <code>forEach</code>.</p> <pre><code>var people = [ .. ]; for(var i /* 1 */ = 0; i /* 2 */ &lt; people.length; i++ /* 3 */) { people[i /* 4 */].updateRecords(); people[i /* 5 */].increaseSalary(); } </code></pre> <p>Marked all 5 occurrences all <code>i</code> inline with comments. We could have so easily eliminated the index <code>i</code> altogether.</p> <pre><code>people.forEach(function(person) { person.updateRecords(); person.increaseSalary(); }); </code></pre> <p>For me the benefit is not in lesser lines of code, but removing needless details from code. This is the same reason why most programmers jumped on the iterator in Java when it was available, and later on the <code>enhanced</code> for loop when it came out. The argument that the same grounds don't hold for JavaScript just doesn't apply.</p>
 

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