What are Javascript closures?When would you use them? | Eklavya Online

What are Javascript closures?When would you use them?

Two one sentence summaries:

  • a closure is the local variables for a function – kept alive after the function has returned


  • a closure is a stack-frame which is not deallocated when the function returns.

A closure takes place when a function creates an environment that binds local variables to it in such a way that they are kept alive after the function has returned. A closure is a special kind of object that combines two things: a function, and any local variables that were in-scope at the time that the closure was created.
The following code returns a reference to a function:

function sayHello2(name)


var text = ‘Hello ‘ + name; // local variable

var sayAlert = function() { alert(text); }

return sayAlert;


Closures reduce the need to pass state around the application. The inner function has access to the variables in the outer function so there is no need to store the information somewhere that the inner function can get it.

This is important when the inner function will be called after the outer function has exited. The most common example of this is when the inner function is being used to handle an event. In this case you get no control over the arguments that are passed to the function so using a closure to keep track of state can be very convenient.