Optimizing common JavaScript code

In this section, we will analyze some performance tips that are not jQuery-specific and can be applied to most JavaScript implementations.

Writing better for loops

When iterating over the items of an array or an array-like collection with a for loop, a simple way to improve the performance of the iteration is to avoid accessing the length property on every loop. This can easily be done by storing the iteration length to a separate variable, declared just before the loop or even along with it, as shown below:

for (var i = 0, len = myArray.length; i < len; i++) { 
    var item = myArray[i]; 
    /*...*/ 
} 

Moreover, if we need to iterate over the items of an array that does not contain falsy values, we can use an even better ...

Get jQuery Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.