Closure:
A closure is created when a function remembers the variables from its outer scope, even after the outer function has finished executing.
function bank(){
let min_bal=500;
function deposit(amt){
min_bal=min_bal+amt;
console.log(min_bal)
}
return deposit
}
const customer1=bank();
customer1(1500);
customer1(500);
ouput:
2000
2500
How can return more than one function ?
we can store the function in a objects. In object we can store functions and properties , we can access them in key value pair.
function bank(){
let min_bal=500
const admin={
deposit:function(amt){
min_bal = min_bal+amt;
}
withdraw:function(amt){
min_bal=min_bal-amt;
}
checkbal:function(){
console.log(min_bal)
}
}
return admin;
}
const cus1=bank();
cus1.withdraw(100);
cus1.deposit(5000);
const cus2=bank();
cus2.withdraw(100);
output:
400
5400
400
Top comments (0)