Monday, October 24, 2011

Creating functions inside loops in Javascript

This is an ongoing effort to make Javascript a more robust programming language. So when one uses JSLint it complains about a number of bad coding practices.

One of its very rare occurrence is the creating of functions inside a loop.
Experienced programmers get into the habit of writing code like this:

var i;
for(i = 0 ; i < someValue; i++) {
  // some operations

  $(".a").onclick = (function() {
    $(this).href = // some manipulated code.

} // end for

While this has become a standard way of operating in Javascript, this is a bad practice, because you are creating functions for every iteration of the loop. 
Since in Javascript, functions are also allocated memory and can be accessed with their name references anywhere in the code, that is after their point of declaration, this coding practice unnecessarily creates many instances (the word instance is also debatable in Javascript, as Object Oriented means differently in here) of the function.

In order to keep the existing functionality, the code can be re-factored to meet the standards in this way:

var doSomething = function(){
  $(".a").onclick = //some manipulated code.

var i;
for(i = 0 ; i < someValue ; i++) {
  // some operations

  $(".a").onclick = doSomething();

} // end for

The beauty of this style of coding is more evident when the function becomes complex and takes in values.

No comments:

Post a Comment