I often find that all the great goodies that JavaScript comes with literally leaves me groping for equivalent luxury in other programming languages. One such super cool concept is that of ‘closure’.

So, what’s a closure? The term closure has several meanings depending on the context it’s being used in. In computer science, in simplest of words, it refers to a first class function that retains access to variables defined in the same scope as the function. Also, I might need to explain the phrase ‘first class function’ – it basically refers to a function that is an object, an instance of a type that defines functions, which enables you to treat a function just like any other object.

Now, let’s use an example to take this further –

function getMultiplier(m){
 return function(n){
  //m in the following statement will always refer
  //to the variable m available in the same scope as this function
  return n*m;

 }
}
var get5x = getMultiplier(5);
get5x(3);//returns 15
get5x(5);//returns 25

From the above code, notice that the function that is created and returned inside getMultiplier, will always have access to the variable m. However it is important to note that we are not just referring to the value of the variable m. Let us look at another example.

function Fruit(aName){
 var name = aName;
 this.getName = function(){
  return name;
 }
 this.setName = function(aName){
  name = aName;
 }
}
var mango = new Fruit("Mango"),//any function in JS can be used as a constructor
    apple = new Fruit("Apple");
mango.getName();//returns Mango
mango.setName("Green Mango");
mango.getName();//returns Green Mango

Observe that in this example, the way we use the variable name, reminds us of private variables. The only way we can access the variable ‘name’ is through the closure functions getName and setName. More importantly it also gives us a clear cut example of how closures work on variables/memory – not just on the values contained in the variables when the function was created. Also note that we have two closure functions defined here, in the same context, sharing the ‘name’ variable.

I hope this explanation gives you enough information on understanding the basics of closures. Closures have a great role to play in object oriented JavaScript. And of course, closures are possible in many other languages, Python being one of the other prominent ones.