DEV Community

subash
subash

Posted on

What is closure

Closure is used to preserve data and create private memory for functions.
“Variables-ஐ பாதுகாப்பாக வைத்துக்கொண்டு, function முடிந்த பிறகும் அவற்றை நினைவில் வைத்திருப்பது.”

example

function bank(){
            let min_bal = 500;


          return   (amt) => {
             min_bal += amt;
               console.log(`current bal is ${min_bal}`)
            }

        }

        const account = bank();
        const sdf = bank();



        sdf(200);
         sdf(200);
        account(300)
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

In this case bank() is outer function and inner function is in return, which is inside the outer function and min_bal variable also inside the outer function , so outer function return the arrow function , then we put bank() function in account variable then,
we should call account as a function , like account(300) also we can able to pass aruguments.

Here i put bank() function in two diff variable, also we can create so many variable , each variable have separated.
min_bal is 500 in sdf add 200 and then again 200 now total amount is 900
min_bal is 500 in account add now total amount is 900 .

two variable keep separate value but function is same .

Top comments (0)