JavaScript Closures

Petr Kostelanský | 19 October 2017
Information and benefits about Closures. Why is bad using global variables and how to use Closures instead.

Sometimes we create global variables to store state but those variables can be used by code that woks with variables with the same name. So, using global variables can cause issues. The solution can be to use Closures.

We can create custom scope that can not be accessed form outside and contains local variables that is stored in stack of function. So, variables that we create can not be changed by logic outside closures. In JavaScript the only way to create new scope is by functions.

We can create closures by different ways:

1) Function expression

var counter = function(){
    var value = 0;
    
    return function(){
    	return value++;
    };
};

var myCounter = new counter();
alert("Count: " + myCounter());   // Count: 0
alert("Count: " + myCounter());   // Count: 1

var myCounter1 = new counter();
alert("Count: " + myCounter1());  // Count: 0

In example above we create two closures. Each of those closures has own scope so that is the reason why we got value 0 a then 1 when we called myCounter() twice.

2) Immediately Invokable Function Expression (IIFE)

var counter = (function(){
    var value = 0;
    
    return function(){
    	return value++;
    };
})();

alert("Count: " + counter());   // Count: 0

IIFE approach is mostly used for managing namespaces and help us to create modules.

Loading ads...