Explain closures?

I cannot understand closures even after reading and re-reading a FEW tutorials on the net, what’s it’s purpose and how do you implement it?

I’m glad I’m not the only one. I know I spent a few days of reading from various sources before it finally started to sink in.

The actual explanantion of how they work, how functions work during invocation , the execution object, the variable object, the scope chain, garbage collection etc, is quite a lot to take in.

A detailed explanation can be found here Javascript Closures

In fact at some point you need to stop reading and try them out for yourself.

The following is an attempt at a simple example. There is more to it.

// Closure example

//  Basically functions have what's called a scope chain.
//  The scope chain links from child to parent all the way to window(global)
//  So in this case fun2 has access to fun1's x and then to global's y

var y = 5; // global variable

function fun1(){ // has access to y

  var x = 0;
  
  return function fun2(){ // has access to x and to y
	
	  alert(y + x);
	  x++;
	
  }

};

var test = fun1(); 
// test calls fun1 and get's the returned function fun2
// test now forms what is known as closure
// it has a returned reference to fun2 which
// in turn has reference to x and to y via it's scope chain.
// the permanent reference has formed a closure.

// test
test(); // 5      5 + 0
test(); // 6      5 + 1

y = 20;
test(); //22     20 + 2

Thanks, the first few paragraphs on that page is the best explanation so far, can you or anyone else tell me of actual situation where this would be needed? Also, it absolutely necessary to learn this or can a JS person get by without t or is there an alternative?

Yes it’s worth learning. Necessary even. Not just for the intentional use of closures but also for the unintentional.

An example of unintentional

<body>
<h2>click on each of these</h2>
<ul>
  <li>LI 1</li>
  <li>LI 2</li>
  <li>LI 3</li>
  <li>LI 4</li>
  <li>LI 5</li>
  <li>LI 6</li>
<ul>

<script type = 'text/javascript'>
var listItems = document.getElementsByTagName('li'),
      len = listItems.length;
	  
for (var i = 0; i <  len; i += 1){

  listItems[i].onclick = function() { alert('Item ' + i); };

}
</script>
</body>

Another example
With closure


var myFunc = (function(){

  var x = the return value of some complicated procedure here;
  
  return function(y){
        
     do something with x  and y here and return the result;
  
  }

}());

Without closure it might look like this

var myFunc = function(y){

  var x = the return value of some complicated procedure here;
  
  do something with x  and y here and return the result;

}

Each time we call the function without closure we have to not only create a variable x but we have to run through that complicated procedure.

With the use of closure x is only run once and a reference kept of it in closure.

A few other uses off the top of my head. Private variables, currying(partial application) and binding.

I’m sure others here can comment. In fact there’s a douglas crockford video which is devoted almost entirely to them, which is well worth a watch. It maybe this one I can’t remember http://googlecode.blogspot.com/2009/03/doug-crockford-javascript-good-parts.html see 0:27

I didn’t want to because I couldn’t think of a good enough example.
Fortunately lighting has struck. I’m watching a recent Douglas Crockford video talk that he gave to Etsy about “The Good Parts”, and closure is nicely covered in there at around the 38 minute mark.
Douglas Crockford 4/27/2011 on Etsy - live streaming video powered by Livestream

To start with, here’s a simple function that returns the name of a digit.


var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

var digit_name = function (n) {
    return names[n];
};

The problem with that code is that since those variables are not within a function, they are at the global scope. Global variables are in constant danger of being clobbered. Not only by yourself, but potentially from other code that you cannot know of or trust, such as adverts for example.

So, remove the array from the global scope by putting the array inside the function.


var digit_name = function (n) {
    var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

    return names[n];
};

Now the names variable is a private variable, but now you’re defining an array of ten items every time you want to retrieve one of them. This is where closure comes in.

With closure, you can return a function that retains knowledge of the variables from within its own scope. This is all built on top of a self-executing function:


var value = (function () {
    return 'value';
}());

So the function is executed immediately, which returns as a result the returned value.

Now instead of returning a value, a function can be returned too.


var digit_name = (function (n) {
    var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

    return function () {
        return names[n];
    };
}());

Now the outer function is executed immediately, which returns as a result the inner function. That returned function retains knowledge of the names variable, and any other variables that are defined in the same scope.

Closure is the most powerful idea in JavaScript, which it got from Scheme.

Some wise words that I heard somewhere is that writing in JavaScript without understanding closure is like writing in Java without understanding classes.

This is one of the nicest explanations of closure that I’ve come across.
How do JavaScript closures work?