Closures in javascript

With closures, we can hide certain properties and methods. As demonstrated in below example, we have hidden the salary variable from outside the self invoking function. In below example, we have hidden the salary variable from outside the parent context. We have exposed only 2 methods using closure - increment and getSalrating. Note that Salary variable value does not reset after every call of increment method. Initial salary assignment happens only once. Due to closure, salary variable remains in the scope of increment and getSalRating methods.

Closures example


//closures
let util = (function () {
    //private members
    let salary = 999;

    //public members
    return {
        increment : function(x) {
            salary += x;
        },
        getSalRating : function(){
            if (salary > 1000)
                return "Salary is good";
            else
                return "Salary is bad";
        }
    }})();

//We can only access public members from outside thus hiding the private members
console.log(util.getSalRating());

let sal = util.increment(20);
console.log(util.getSalRating());
sal = util.increment(20);
console.log(util.getSalRating());

Complex problems, Simple Solutions