DEV Community

Cover image for Closure in JavaScript
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

Closure in JavaScript

closure is same as Encapsulation java.
Global variables can be made local (private) with closures.

 function bank(){
            let balance=500;

            const service={
                deposit : function(amt){
                    balance+=amt;
                    console.log(balance);
                },
                withdraw : function(amt){
                    balance-=amt;
                    console.log(balance);
                },
                viewbalance : function(){
                    console.log(balance);
                }
            }

            return service;
        }
        const person1= bank();
        person1.deposit(1000);
        const person2=bank();
        person2.withdraw(3000);
        const person3=bank();
        person3.viewbalance();
Enter fullscreen mode Exit fullscreen mode

output:

1500
-2500
500
Enter fullscreen mode Exit fullscreen mode

Top comments (0)