Tuesday, January 29, 2013

Yo dawg, I herd you like loops, so jQuery put a loop in your code

Do You Know When You Are Looping in jQuery?


A common misunderstanding I see when looking at jQuery code is a lack of understanding about loops.

Most developers seem to grok the .each() method, but that can be both a good and a bad thing.

It is important to know the difference between an Implicit Loop and an Explicit Loop.

Implicit Loops


The following code snippet is something that you would typically see from a jQuery developer. You are probably aware of the "Find something, Do something" mentality of jQuery. The code first queries the DOM for all elements that have the widget class and then jQuery proceeds to implicitly loop over all of the elements matching the query and adds the highlight class.


Explicit Loops


An explicit loop in jQuery is much more obvious. The code for the loop is visible via the .each method. This is pretty straight forward and typically developers understand that there could be performance issues for any code inside the .each loop.


Indications of Confusion


You can start to tell if a developer doesn't realize the different between implicit and explicit loops if you start to see something like the following code snippet.


In this example there is no reason for using the .each method because there was nothing inside of the loop that is unique. A simple implicit loop, like the following snippet, would have been sufficient.


Method Overloads


Knowing about implicit loops also sheds some light of the following situation.

In the following snippet of code jQuery is looping over the matches elements twice (once to change the color and a second time to change the font-size).


If you needed to write code similar to the previous, you could do something like the following instead and use the "overloaded" .css method that takes an object containing the key/value pairs you wish to apply.


It might seem like the above snippet is slower than the following, but when it comes down to it they are about the same speed. I tend to recommend the last snippet as it is cleaner and more flexible down the road as you can pass in a variable containing all your options.

As a side note, it is preferable to use the .addClass() / .removeClass() / .toggleClass() methods instead of the .css() method to manipulate your elements unless you need to change their width/height/position/etc. The output of the .css() method gets attached to the style attribute of your element. The browser is highly optimized to deal with CSS classes and also whoever is maintaining will thank you for using classes instead of hardcoding style in your code.

Conclusion


Although these concepts may seem very basic, I often run across code that doesn't require an .each method. It is helpful knowing some of these under the cover concepts. I hope you found it insightful.

No comments:

Post a Comment