How closure works in JavaScript ?
In this article, we will discuss about the closures working JavaScript. Let us first understand what exactly closures are and basic details which are associated with closures in JavaScript.
A Closure is a combination of a function enclosed with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created at run time. In other words, closure is just a fancy name for a function that remembers the external things used inside it.
Let us look at some examples to understand how closures work in JavaScript.
Example 1:
- In this example, we will declare a closure that would eventually access an outer variable balance from the outer function.
- After using the outer variable in an inner most function, that closure will help us deduct 100 from it, whenever that outer function is called.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Closures</h2>
<button type="button" onclick="initaccount()">
Click Me!
</button>
<p id="demo"></p>
<script>
function initaccount() {
var balance = 1000;
function currentbalance() {
balance = balance - 100;
alert(balance);
}
currentbalance();
}
</script>
</body>
</html>
Output:
Explanation: In the above example, currentbalance() can access outer variable balance hence balance is deducted by 100 each time initaccount() method is called.
Example 2: Closures can be nested as well as in below example. Here in the example both outerfunction() and innerfunction() has access to counter variable , hence on calling Counter() both outerfunction() and innerfunction() increments the value of counter. In this context, we can say that closures have access to all outer function scopes.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Closures</h2>
<button type="button" onclick=" Counter()">
Click Me!
</button>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function Counter() {
var counter = 0;
function outerfunction() {
counter += 1;
document.getElementById("demo1").innerHTML
= "outercounter = " + counter +
"from outerfunction " ;
function innerfunction() {
counter += 1;
document.getElementById("demo2").innerHTML
= " innercounter = " + counter +
"from innerfunction ";
};
innerfunction();
};
outerfunction();
};
</script>
</body>
</html>
Output: