Picture

Hi, I'm Boopathi Rajaa.

Hacker, Dancer, Biker, Adventurist

JavaScript Closures

Well, I was just wondering how to start with the explanation of closures. Have heard a saying sometime back. It goes like this

If you can’t explain it to a six-year old, you really don’t understand it yourself

Sorry if I’m not making my context clear. Lets start with an example as usual.

function myFunction(someVar) {
  var temp = 3;
  function myFunction2(someVar2) {
   alert(someVar + someVar2 + (++temp));
  }
  myFunction2(10);
 }
myFunction(2);

Now this piece of simple code when executed, always alerts 16. The inner function “myFunction2” can access someVar, someVar2 and temp. Now this is not a CLOSURE. A CLOSURE is when you return the inner function. Lets see another example.

function myFunction(someVar) {
  var temp = 3;
  return function (someVar2) {
    alert(someVar + someVar2 + (++temp));
  }
}
var myFunction2 = myFunction(2);
myFunction2(10);

Here myFunction2 is the Closure. The above code will still alert 16, for myFunction2 can access someVar and temp even though it is no longer directly inside the scope. Here temp will be incremented each time you call myFunction2. And, to quote, it is possible to create more than one closure function, either by returning a list of them or by setting them to global variables. Then all of these will refer to the same “someVar” and the same “temp”. They don’t make their own copies.

Now lets see the part that isn’t obvious.

In the piece of code above, someVar is a number. As with other literals/variables in JavaScript, when myFunction is called, the number someVar is copied into myFunction as its argument someVar. On the other hand, JavaScript always uses references when dealing with Objects. So when you called myFunction with an Object, the closure it returns will always reference an Object. Hmm now it would seem too obvious I suppose. Now lets get rid of the boring theory and see an example.

function myFunction(someVar) {
  var temp = 3;
  return function(someVar2) {
    alert(someVar + someVar2 + temp);
    someVar.memb = someVar.memb ? someVar.memb + 1 : 1 ;
    alert(someVar.memb);
  }
}
var sample = new Number(2);
var myFunction2 = myFunction(sample);
myFunction2(10);

As expected, each time you call myFunction2, someVar.memb will be incremented. What might not be expected is that someVar is simply referring the same object as the sample variable. After a couple of calls to myFunction2, sample.memb will be 2. Now this forms the basis for memory leaks in HTML objects, which is a little beyond the scope of this topic. ahem.. ahem…

problems understanding ?

JavaScript Closure for Dummies is the article that explains about closures in detail. The explanation posted there is much better than anything I’ve written here.