So, I had a debate with one engineer about a loop in JavaScript. The problem was building native for the loop and a prototype of each () method. Now I know that there are many documents / blogs for each and for each, but this debate is somewhat different, and I would like to hear what some of you think.
Take the following loop, for example
Example 1
var someArray = [blah, blah, blah,...,N]; var length = someArray.length; for(var index = 0; index < length; index++){ var value = someFunction(someArray[index]); var someOtherValue = someComplicatedFunction(value, someArray[index]);
For me this happens to be second nature, mainly because I learned how to code C , and it transferred me. Now I use For-each in both C # and Java (carry me, I know that we are talking about JavaScript here ..), but whenever I hear about loops, First I think about this guy. Now consider the same example written using Prototype each ()
example 2
var someArray = [blah, blah, blah,β¦..,N]; someArray.each(function(object){ var value = someFunction(object); var someOtherValue = someComplicatedFunction(value, object);
In this example, right off the bat, we see that the design has less code, but I think every time we scroll through the object, we must create a new function to solve the operation in question. Thus, it will be bad to bring down collections with a large number of objects. So my buddy argument was that Example 2 is much easier to understand and actually cleaner than Example 1 because of its functional approach. My argument is that any programmer should be able to understand Example 1, since it is studied in programming 101. Thus, the lighter argument is not applied, and Example 1 works better than Example 2 . Then why bother with # 2 . Now, after reading it, I found out that when the size of the array is small, the overhead for example 2 is negligible. However, people kept talking about the lines of code you write less and that Example 1 is error prone. I still do not buy these reasons, so I wanted to know what you guys think ...