Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 263
Sam Avatar asked Dec 26 '22 05:12

Sam


1 Answers

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.

like image 173
apsillers Avatar answered May 07 '23 11:05

apsillers