Closure in Javascript
What is a Closure?
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
In JavaScript, every running function, code block {...}
, and the script as a whole have an internal (hidden) associated object known as the Lexical Environment.
The Lexical Environment object consists of two parts:
- Environment Record — an object that stores all local variables as its properties (and some other information like the value of
this
). - A reference to the outer lexical environment, the one associated with the outer code.
When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can’t get at the data from an outside scope except through the object’s privileged methods. In JavaScript, any exposed method defined within the closure scope is privileged.
Closures can also be used to create stateful functions whose return values may be influenced by their internal state.
Examples:
var add = (function () {
var counter = 0;
return function () {counter += 1; return counter}
})();add();
add();
add(); // the counter is now 3