O'Reilly logo

jQuery Design Patterns by Thodoris Greasidis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required