Wednesday, December 12, 2012

What are Closures in Javascript


Closures in javascript considered as an advanced feature. Closures is little tricky to understand. So understanding closure is an important thing.
Let’s look at a simple example

function start() {
  var text = "Hello World";
  function getText() {
    alert(text);
  }
  getText();
}
start ();

this is a very simple straight forward example. start() defines a local variable “text and a function getText(). And then it calls the getText function which returns the variable “text” which is not local to function getText but which is accessible from the outer scope. This is functional scoping.  
Consider the following example

function start() {
  var text = " Hello World ";
  function getText() {
    alert(text);
  }
  return getText;
}

var myFunc = start();
myFunc();

Basically local variables within a function exist only within the functions execution period.  But since myFunc() outputs an alert, it seems that it still has the access to the variable “text”.  The reason is the variable myFunc() has become a closure.

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).