Closures in JavaScript

Posted By :Asheesh Bhuria |27th June 2019

A closure is simply a function which is bundled together with its lexical environment (it’s surrounding state). Using closures, we can access variables and methods defined in outer function’s scope. Closures are created automatically during function creation time.

 

Closures can be used by returning a function inside another function call. The inner function which is returned will have access to the scope of the outer function. 

 

We can get better understanding of closures from below use cases,

 

1. Passing different values to the lexical environment of a function can provide flexibility in terms of function usage.  

 

Suppose there are two scenarios where we need to multiply a set of data with two different numbers, rather than creating two different functions which execute the same logic (but with different variables) we can make use of closure.

 

function multiply(multiplier) {
    return innerFunction(number) {
        return number*multiplier;
    }
}

let multiplyWithTwo = multiply(2);
let multiplyWithThree = multiply(3);

console.log(multiplyWithTwo(2)); // 4
console.log(multiplyWithThree(2)); // 6
 

 

2. Closures are essential when we want to follow concepts of OOP in JS. In javascript there is no concept of defining private entities, but using closure we can restrict variable access. 

 

When we declare or define any variable in the outer function, we can only access the variables from within the function (including the closure function.) So when we call a closure function, such a variable exists only within the scope of the closure and hence only closure can use variable. This restricts the access to the variable.

 

If we want to access value of such variables, from oustide the closure, we can simply return a method in closure which returns the variable.

 

Here is an example:- 

function outerFunction(privateVar) {
    return innerFunction() {
        return {
            getPrivateVar: function() {
                return privateVar;
        }
    }
}
 

 

 


About Author

Asheesh Bhuria

Asheesh Bhuria is a software engineer. With his knowledge in new technologies he excels in MEAN Stack development.

Request For Proposal

Sending message..

Ready to innovate ? Let's get in touch


Notice: Undefined index: HTTP_REFERER in /var/html/www/AI/wp-content/themes/oxides-child/functions.php on line 272

Notice: Undefined index: HTTP_REFERER in /var/html/www/AI/wp-content/themes/oxides-child/functions.php on line 272

Notice: Undefined index: HTTP_REFERER in /var/html/www/AI/wp-content/themes/oxides-child/functions.php on line 272

Notice: Undefined index: HTTP_REFERER in /var/html/www/AI/wp-content/themes/oxides-child/functions.php on line 272

Chat With Us