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 in JavaScript is a feature where an inner function has access to the variables of its outer (enclosing) function, even after the outer function 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
Thanks for the link, Jon! The definition was kept simple for beginners. A more precise version would include lexical scope, but the main idea is still correct.
Top comments (4)
Unfortunately, this is not correct.
Misconceptions About Closures
Thanks for the link, Jon! The definition was kept simple for beginners. A more precise version would include lexical scope, but the main idea is still correct.
Saying a closure is a function is not correct.
That's a fair correction, Jon! A closure isn't the function itself — it's the combination of the function and its lexical environment.