Saturday, September 3, 2011

Some interesting usages of closure in Javascript

Closures are one of the most powerful features of ECMAScript (Javascript), but they can not be exploited without properly understanding them. Some very interesting usage of closures for circumventing few problems are listed below.
  1. Problem: Add click listeners to a array of DOM elements, clicking on element should alert index of element in array.
Wrong solution :


for(var i=0;i<elArray.length;i++){
elArray[i].on('click',function(){alert(i)});
}


The problem here is that clicking on any node alerts the size of array instead of its index. Reason being, value of 'i' is equal to elArray.length on termination of loop and ever after.


Right Solution
inducing closure is the key here... we can use anonymous function to induce the scope needed to create the multiple closure


for(var i=0;i<elArray.length;i++){
elArray.on('click',(function(){
return function(){
alert(i);
};
})())
}


this simply works, but might not be very intuitive to do. There are other ways of achieving the same but I like this best. Would love to hear about benefits of other approaches that you might figure out.