In JavaScript, it is allowed to return a function within a function.
functiongreet(name){functiondisplayName(){console.log("Hi "+name)}returndisplayName;//returning a function}constg1=greet("Varun");console.log(g1);g1();Output:displayName(){console.log("Hi "+name)}HiVarun
In the above program, the greet() function is returning the displayName function definition .
The returned function definition is assigned to the g1 variable. When you print g1 using console.log(g1), you will get the function definition.
To call the function stored in the g1 variable, we use g1() with parentheses.
What is a Closure?
A closure is a function that remembers the variables from its outer scope even after that outer scope has finished executing.
functionouter(){letcount=0;// This variable lives in outer scopefunctioninner(){count++console.log(count);}returninner}constcounter1=outer();// outer() finishes, but count isn't gone!counter1();counter1();counter1();constcounter2=outer();counter2();counter2();counter2();Output:123123
outer() runs once.
But count is not destroyed.
Because inner() remembers it.
That memory = closure.
Even though outer() has returned, inner still holds a live reference to count. That's a closure.
functionbank(name,totalAmt){return{deposit:function(amount){totalAmt=totalAmt+amount;returntotalAmt},withdraw:function(amount){totalAmt=totalAmt-amount;returntotalAmt},checkbal:function(){console.log(`Hi ${name}, Your total amount is ${totalAmt}`);}}}constvarunacc=bank("Varun",5000)console.log(varunacc.deposit(1000));console.log(varunacc.withdraw(500));varunacc.checkbal();Output:60005500HiVarun,Yourtotalamountis5500
Top comments (1)
Unfortunately, this is not correct.
Misconceptions About Closures