Closure in JavaScript
A closure is the combination of a function and its lexical environment, allowing the function to access variables from its outer scope even after the outer function has finished executing
A closure allows an inner function to use the variables of its outer function even after the outer function has returned
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<script>
function bank(){
let min_balance=500;
function deposit(amt){
min_balance=min_balance + amt;
console.log(min_balance);
}
return deposit;
}
const deposit1=bank();
deposit1(500);
deposit1(2000);
const deposit2=bank();
deposit2(700);
</script>
</body>
</html>
Output:
1000
3000
1200
<script>
function actions() {
let min_balance = 1000;
return {
deposit: function(amt) {
min_balance += amt;
console.log("Balance:", min_balance);
},
withdraw: function(amt) {
min_balance -= amt;
console.log("Balance:", min_balance);
},
check_balance: function() {
console.log("Balance:", min_balance);
}
};
}
const customer1 = actions();
customer1.deposit(100);
customer1.withdraw(50);
customer1.check_balance();
</script>
Output:
Balance: 1100
Balance: 1050
Balance: 1050
Top comments (0)