I am most certainly not a Javascript purist, I love jQuery just as much as the next developer does, but that doesn’t mean I use it for everything. One thing that really gets under my skin is when jQuery is used to unnecessarily loop through and array or object.
It’s 2014, not 2008, we no longer have to use library methods because of browser API constraints like we once did for older versions of IE. Using jQuery.each() for looping through an array or object is quite an expensive operation and poor in terms of performance, this is one of those situations where native methods and conditions which are well supported eclipse jQuery 1000:1.
This JSPerf benchmark shows in Chrome and Firefox just how much of a difference using a native for loop makes. See below for the results I got on the latest version of Chrome on a Mac. The difference is like night and day. I know that a for loop might require more typing and not look as clean, but if you care about performance, then you won’t always go for the easiest method.
Good:
var myArray = ["apple", "banana", "orange", "grapefruit", "pear", "pawpaw"];
for (var i = 0, len = myArray.length; i < len; ++i) {
console.log(myArray[i]);
}
Beyond bad (avoid this kind of loop for arrays please):
var myArray = ["apple", "banana", "orange", "grapefruit", "pear", "pawpaw"];
for (var i in myArray) { }
At all costs you should avoid using a for..in loop if you can for arrays. Trust me, you don’t want to see the performance benchmarks on a for..in loop, they’re incredibly slow and the use of this kind of loop in favour of a standard for loop can almost always be avoided.