4

I understand the theoretical concept behind Javascript closures like there is a variable that can only be accessed by inner function and all that...so kind of implementing private variable in JS.

But I wanted to understand some practical examples where Closures are actually helpful. So I need example not to understand what closure is, but practical use cases for Closure.

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) I think that question should have been closed as well as not constructive, but it's here. – gdoron Mar 15 '13 at 07:25
  • This question might be more suitable at [programmers.se]. It feels too open-ended here. – John Dvorak Mar 15 '13 at 07:27
  • Two things 1)so that their values not get modified unintentionally by other functions accessing them. 2) What will happen if you installed a browser plugin that uses javascript has a global variable with same name as your variable? – Gaurav Pandey Mar 15 '13 at 07:32

1 Answers1

10

Two standard examples :

1) keeping variables for callbacks :

   var a = [1, 2, 3];
   for (var i=0; i<a.length; i++) {
      (function(j){
          setTimeout(function(){
             console.log(a[j]);
          }, 1000*j);
      })(i);
   }

2) keeping variables private

var obj = (function(){
    var private = 0;
    return {
        increment: function(){ private++; },
        getValue:  function(){ return private; }
    }
})();

In fact the simplest is to remember one thing : what is a closure, that is a link from a function to the scope in which it was created. This link prevents the scope (and its variables) to be garbaged and it's the only accessible link to this scope (hence the privacy).

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758