Javascript for loop vs jQuery for each

jquery

Javascript for loop vs jQuery for each

Web developers often come across looping through data at client side. People generally use native Javascript coding for loop, or jQuery for each.

Javascript For Loop. Example

var names= ["anoop", "kumar", "rai"];
var i;
var text="";
for (i = 0; i < cars.length; i++) {
    text += names[i] + ",";
}
document.write(text);

Result-> “anoop,kumar,rai”

 

jQuery For Each. Example

var names= ["anoop", "kumar", "rai"];
var i;
var text="";
jQuery.each(names, function(i, str) {
   text += str + ",";
});
document.write(text);

Result-> “anoop,kumar,rai”

 

Now both are rendering same result, so its time to decide which one to use. Below are my points that should be kept in mind in order while choosing Javascript or jQuery looping mechanism.

  • Since Javascript is native coding, so its obviously faster than jQuery. But this difference is reflective when you have huge number of records, i.e. 1000 or more. So, if there is huge number of records then Javascript for loop should be preferred, else go for jQuery .each()
  • One thing that .each() allows you to do that can’t be done with a for loop is chaining. Plain JS loops are still slightly faster, but whether that weighs up to the added readability of .each() (and chaining) is debatable.
  • $('.rows').each(function(i, el) {
        // do something with ALL the rows
    }).filter('.even').each(function(i, el) {
        // do something with the even rows
    });
    
  • One thing you do get with .each() is automatic local scoping (because you are invoking an anonymous function for every object), which in turn means if you are creating even more anonymous functions on every iteration, you never have to worry about your handlers sharing a variable. In my opinion, jQuery.each() acts more like a closure than an iterator.

About Anoop Kumar Rai