Thursday, September 5, 2013

Replacing the jQuery.each function

http://api.jquery.com/jQuery.each/

Compare the following examples:

Example 1 (Using jQuery):

   $("section").each(function(index, element){
       //do something with element
   });

Or even better
   $.each($("section"), function(index, element){
       //do something with element
   });

Example 2 (Native javascript):

   var elements = document.querySelectorAll("section");
   for(var i=0;i<elements.length; i++){
      var element = elements[i];
   }

Note that these pieces of code do the exact same thing.  They loop through all the elements in an array.  In fact the first solution looks very elegant.  Some might even argue it's the functional way a javascript developer should code.

Nobody, however, should argue which one gets better performance when run in browser.

Honestly, anyone can read the examples, but who really benefits from code like Example 1?  It's not the page viewer, because the client had to download a 45kb library to get "foreach" functionality that makes the page run slower.  It's also not the developer, because the developer missed out on making their code faster. I guess the answer is that nobody truly benefits except for beginners, who get shortchanged unknowingly.

There is however one more suggestion:

 [].forEach.call( nodeListReference, function (node) {
  // now do whatever you want to do with node
});

Feel free to comment below. All opinions are valid and welcome.

3 comments:

  1. like vanilla.js http://vanilla-js.com/http://vanilla-js.com/

    ReplyDelete
    Replies
    1. Good call. Better add that library to my toolset.

      Delete
  2. Your loop is pretty inefficient though as it reads the length of the array on each iteration and querySelectorAll doesn't return a live node list but a static one. As in most cases the order is irrelevant I prefer to use a while on a cached length variable. As in var elements = document.querySelectorAll("section");var all = elements.length; while(all--) {/* do stuff with elements[all]; */} - thr trick is that when all is 0 it ends the while loop because of the truthy nature. I do also like that this way I don't have the issue of length being the amount of elements+1.

    ReplyDelete