A closure is created when a function remembers the variables from its outer scope, even after the outer function has finished executing.
How Closures Work
- An outer function creates a local variable.
- An inner function inside the outer function uses that variable.
- The outer function returns the inner function.
- The variable stays in memory because the inner function still needs it.
<script>
function bank() {
let min_balance = 500;
const actions = {
deposit: function (amt) {
min_balance = min_balance + amt;
},
withdraw: function (amt) {
min_balance = min_balance - amt;
},
checkbalance: function () {
console.log(min_balance);
}
}
return actions;
}
const customer1 = bank();
customer1.deposit(100);
customer1.checkbalance();
customer1.withdraw(200);
customer1.checkbalance();
</script>
Top comments (0)