DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

Closure function in JS

JavaScript Nested Function :

  • A function can also contain another function. This is called nested function.
function greet(name) {

        function displayName() {
                console.log("Hi " + name)
        }

        displayName();

}

greet("Varun");

Output :
Hi Varun

Enter fullscreen mode Exit fullscreen mode

Returning a function :

  • In JavaScript, it is allowed to return a function within a function.
function greet(name) {

        function displayName() {
                console.log("Hi " + name)
        }

        return displayName; //returning a function

}

const g1 = greet("Varun");
console.log(g1);
g1();

Output :
displayName() {
                console.log("Hi " + name)
        }
Hi Varun
Enter fullscreen mode Exit fullscreen mode
  • 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.
function outer(){
        let count = 0; // This variable lives in outer scope

        function inner(){
                count++
                console.log(count);
        }
        return inner
}

const counter1 = outer(); // outer() finishes, but count isn't gone!
counter1();
counter1();
counter1();

const counter2 = outer();
counter2();
counter2();
counter2();

Output :
1
2
3
1
2
3
Enter fullscreen mode Exit fullscreen mode
  • 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.
function bank(name,totalAmt)
{
        return {
                deposit : function(amount){
                        totalAmt = totalAmt+amount;
                        return totalAmt
                },
                withdraw : function(amount){
                        totalAmt = totalAmt-amount;
                        return totalAmt
                },
                checkbal : function(){
                        console.log(`Hi ${name}, Your total amount is ${totalAmt}`);
                }       
        }


}

const varunacc = bank("Varun",5000)
console.log(varunacc.deposit(1000));
console.log(varunacc.withdraw(500));
varunacc.checkbal();

Output :
6000
5500
Hi Varun, Your total amount is 5500
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

A closure is a function that remembers the variables from its outer scope even after that outer scope has finished executing.

Unfortunately, this is not correct.