What are Closures in javascript ?

So what really are closures ?
A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited. A closure is the local variables for a function — kept alive after the function has returned. In short, Whenever you use function inside another function, a closure is used.

Now lets understand this better with some examples,

Example 1 : The following code returns a reference to a function: (jsfiddle link)

function sayHello(name) {
  var text = 'Hello ' + name; // local variable
  var sayAlert = function() { alert(text); }
  return sayAlert;
}
say = sayHello('Yasser');
say(); // alerts "Hello Yasser"

Explanation : The above code has a closure because the anonymous function function() { alert(text); } is declared inside another function, sayHello() in this example. In JavaScript, if you use the function keyword inside another function, you are creating a closure.

In JavaScript, if you declare a function within another function, then the local variables can remain accessable after returning from the function you called. This is demonstrated above, because we call the function say2() after we have returned from sayHello(). Notice that the code that we call references the variable text, which was a local variable of the function sayHello().

Example 2 : (Jsfiddle Link)

function say501() {
  // Local variable that ends up within closure
  var num = 500;
  var sayAlert = function() { alert(num); }
  num++;
  return sayAlert;
}

say = say501();
say();​

Explanation : This example shows that the local variables are not copied — they are kept by reference. It is kind of like keeping a stack-frame in memory when the outer function exits!

Further Reading :
How do JavaScript closures work?