DEV Community

Veera Ganapathi
Veera Ganapathi

Posted on

Closure in JavaScript

What is Closure?

A closure is the combination of a function and its lexical environment, allowing the function to access variables from its outer scope even after the outer function has finished executing.

  • Retains access to outer function variables.
  • Preserves the lexical scope.
  • Allows data encapsulation and privacy.
  • Commonly used in callbacks and asynchronous code.
function bank() {

            let min_balance = 500;

            const actions = {

                deposit: function (amt) {
                    min_balance = min_balance + amt;
                },

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

                }



            }
            return actions;
        }

        const customer1 = bank();
        customer1.deposit(1000);
        customer1.checkbalance();

Output:
1500
Enter fullscreen mode Exit fullscreen mode

Top comments (0)