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.
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
widgetclass and then jQuery proceeds to implicitly loop over all of the elements matching the query and adds the
An explicit loop in jQuery is much more obvious. The code for the loop is visible via the
.eachmethod. This is pretty straight forward and typically developers understand that there could be performance issues for any code inside the
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
.eachmethod because there was nothing inside of the loop that is unique. A simple implicit loop, like the following snippet, would have been sufficient.
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"
.cssmethod 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
.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
styleattribute 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.
Although these concepts may seem very basic, I often run across code that doesn't require an
.eachmethod. It is helpful knowing some of these under the cover concepts. I hope you found it insightful.