title: Comparing javascripts native "for loop" to prototype's each()
body: <p>So I was having a debate with a fellow engineer about looping in JavaScript. The issue was about the native <em>for loop</em> construct and prototype's <em>each()</em> method. Now I know there are lots of docs/blogs about <em>for</em> and <em>for-each</em>, but this debate is somewhat different and I would like to hear what some of you think.</p>
  
  <p>Let's take the following loop for example</p>
  
  <p><em>example 1</em></p>
  
  <pre><code>var someArray = [blah, blah, blah,...,N];
  var length = someArray.length;
  
  for(var index = 0; index &lt; length; index++){
      var value = someFunction(someArray[index]);
      var someOtherValue = someComplicatedFunction(value, someArray[index]);
      //do something interesting...       
  }
  </code></pre>
  
  <p>To me, this comes second nature mainly because I learnt how to code in <strong>C</strong> and it has carried me through. Now, I use the <em>For-each</em> in both <strong>C#</strong> and <strong>Java</strong> (bear with me, I know we are talking about JavaScript here..) but whenever i hear <em>for loops</em>, i think of this guy first. Now lets look at the same example written using Prototype's each()</p>
  
  <p><em>example 2</em></p>
  
  <pre><code>var someArray = [blah, blah, blah,…..,N];
  someArray.each(function(object){
      var value = someFunction(object);
      var someOtherValue = someComplicatedFunction(value, object);
      //do something interesting...   
  });
  </code></pre>
  
  <p>In this example, right off the bat, we can see that the construct has less code, however, <strong>i think</strong> each time we loop through an object, we have to create a new function to deal with the operation in question. Thus this would preform badly with collections with large number of objects. So my buddy's argument was that  <strong>example 2</strong> is much easier to understand and is actually cleaner than <strong>example 1</strong> due to its functional approach. My argument is that any programmer should be able to understand example 1 since it is taught in programming 101. So the easier argument doesn't apply and <strong>example 1</strong> performs better than <strong>example 2</strong>. Then why bother with <strong>#2</strong>. Now after reading around i found out that when the array size is small the overhead for <strong>example 2</strong> is minuscule. However people kept on talking about the lines of code you write is less and that <strong>example 1</strong> is error prone. I still don't buy those reasons, so I wanted to know what you guys think…</p>