Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical usage/examples of Javascript closures

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.

like image 653
copenndthagen Avatar asked Jan 14 '23 22:01

copenndthagen


1 Answers

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

like image 107
Denys Séguret Avatar answered Jan 19 '23 12:01

Denys Séguret