I read this on SO
Closures are a difficult concept to come to grips with on the first try
Surely they are trickiest! So, I was working on one of the JavaScript closures exercise
//What changes required to for loop so that triggering loop1 will give output as 1
for(var i=0;i<10;i++)
$(document).on('loop'+i, function(){
console.log(i);
})
$(document).trigger('loop1');
Above will output 10
. Here basically, I am triggering event loop1
and I want the output to be 1
. Changes I tried on top of above is
for(var i=0;i<10;i++)
$(document).on('loop'+i, (function(){
return function(){console.log(i)}
})());
$(document).trigger('loop1');
But that didn't helped either. It is still giving me 10
. What should i do to achieve the required output?