DEV Community

Cover image for JS CLOSURE:
Keerthana M
Keerthana M

Posted on

JS CLOSURE:

CLOSURE:

  • A closure in JavaScript is a function that retains access to variables from its outer scope even after that outer function has finished executing.
function bank(){
            let min_balance=500;
            function deposit(amt){
                min_balance=min_balance + amt;
                console.log(min_balance);
            }
            return deposit;
        }
        const deposit1=bank();
        deposit1(500);
        deposit1(2000);

        const deposit2=bank();
         deposit2(700);
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

1000
3000
1200

<script>
function actions() {
    let min_balance = 1000;

    return {
        deposit: function(amt) {
            min_balance += amt;
            console.log("Balance:", min_balance);
        },

        withdraw: function(amt) {
            min_balance -= amt;
            console.log("Balance:", min_balance);
        },

        check_balance: function() {
            console.log("Balance:", min_balance);
        }
    };
}

const customer1 = actions();

customer1.deposit(100);
customer1.withdraw(50);
customer1.check_balance();
</script> 
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
Balance: 1100
Balance: 1050
Balance: 1050

Top comments (0)