Study Guide: JavaScript->Closures

JavaScript closures

In programming languages having first-class functions, closures (that are also called function closures or lexical closures) are a technique for implementing lexically-scoped name binding. Concerning its operation, a closure is nothing but a data structure storing a function together with an environment, which maps all associating each free variable of the function (that are used locally, but defined in an enclosing scope) with the value or storage location the name was bound to at the time the closure was created. A closure allows the function to access those captured variables through the closure's reference to them, even when the function is invoked outside its scope.

More technically, a closure is a stack frame of a function that is not deallocated when it returns.[1]


function sayHello(name) {
    var text = 'Hello, ' + name + '!';
    var sayAlert = function { alert(text); }
    return sayAlert;
var say = sayHello('John');

alert(say.toString);    // Returns the code of the anonymous function

The function reference variable say references to both the function that alerts and to its closure! The closure is created by JavaScript, as the anonymous function is created inside another function. As the anonymous function needs its variables and those "inherited" from its enclosing function, the closure is necessary to provide it with these data. It is also possible to visualise the code of the function (see the last alert statement).

What makes it difficult to understand to many people is that in JavaScript, a function reference has also a hidden reference to the closure it was created in. This is similar to delegates that are a method pointer plus a secret reference to an object.

See also


  1. ? Morris Johns. "JavaScript Closures 101- they're not magic" (in English) (HTML). JavaScript Kit. Retrieved 2015-03-17. 

Further reading

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.



Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.

Manage research, learning and skills at defaultLogic. Create an account using LinkedIn or facebook to manage and organize your Digital Marketing and Technology knowledge. defaultLogic works like a shopping cart for information -- helping you to save, discuss and share.

  Contact Us