Sam
Sam

Reputation: 55

Benefits of .each() function in jQuery over traditional "for" loops

One of my colleague suggested me to use jQuery .each() function over javascript for loop to traverse through DOM elements on my page, I am not a newbie in jQuery, but never understood the real reason behind why developers tend to use .each() over for loop of javascript. Can anyone explain it to me?

Upvotes: 4

Views: 589

Answers (5)

gdoumenc
gdoumenc

Reputation: 599

There is also, for me, an important benefit closure side effect if you use each instead of for.

Consider the code below (I'm using coffeescript as I'm found of..) which alerts on all links with its href value:

$("a").each (i, e)->
  href = $(e).attr('href')
  $(e).on "click" alert(href)

If you "translate" it into a simple for loop like :

for e in $("a")
  href = $(e).attr('href')
  $(e).on "click" alert(href)

This code won't work as the href variable is not enclosed in a closure...

Upvotes: 0

apsillers
apsillers

Reputation: 115940

If you want to iterate using a for loop, you have to increment the index:

for(var i=0; i<arr.length; ++i) {

and then you have to get the actual value using the index:

var value = arr[i];

.each does both of these for you and passes the values into a function:

$(...).each(function(i, value) {
    // actual interesting part of the loop...
});

It simply saves you the boilerplate code of incrementing the index and getting the value at that index.

The variables defined in an .each function are also closed over (i.e., within a closure), so the equivalent code (considering looping and variable closure, plus setting this, as well as breaking on a false return value) might be something like:

(function() {
    for(var i=0; i<arr.length; ++i) {

        var ret = (function(index, value) {
            // actual interesting part of the loop...
        }).call(arr[i], i, arr[i]);

        if(ret === false) break;
    }
})();

which is quite a bit more to type.

In terms of execution performance, .each is (unsurprisingly) slower than a raw for loop, because it does much more than a raw for loop.

Upvotes: 6

Suresh Atta
Suresh Atta

Reputation: 121998

Its very easy to use

But it is slow as shown in this test result. http://jsperf.com/jquery-each-vs-for-loop/214

Upvotes: 2

Bergi
Bergi

Reputation: 664484

It's slower, but more expressive (shorter) and it also sets up closures. Also, on jQuery collections it integrates well into chaining; while for plain arrays I would suggest using the native .forEach method.

Upvotes: 1

Matyas
Matyas

Reputation: 13702

Because it is easier & cleaner to do

$jqExpr.each(function(i, el){
   /* YOUR CODE */
});

than

for(var i=0; i < $jqQExpr.length; i++){
  el = $jqExp[i];
  /* YOUR CODE */
}

Upvotes: 1

Related Questions