Understanding Closure
Closure basically is the scope determination where inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.
function addTemplate(x) {
return function(y) {
return x + y
}
}
var addGenerator = addTemplate(2);
var nextAddGenerator = addTemplate(3);
// Explanation: here x in addTemplate is set as 2 and 3 respectively and inner function is stored in addGenerator
console.log(addGenerator(5)); // 7
console.log(nextAddGenerator(10)); //13
// Explanation: Here inner returned function is executed but utilizing benefit of closure where outer variable x is accessed (i.e 2 and 3 respectively) which can ultimate add y (i.e. 5 and 10 respectively) that results in sum 7 and 13 respectively
Understanding it’s Use Case
Closures is useful in hiding implementaion detail in Javascript. In other words, it can be useful to create private variables or functions.
var counter = ( function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
};
})();
console.log(counter.value()); // 0
counter.increment();
counter.increment();
console.log(counter.value()); // 2
counter.decrement();
console.log(counter.value()); // 1
// Explanation: Here increment(), decrement() and value() becomes public function because they are included in the return object, whereas changeBy() function becomes private function because it is not returned and only used internally by increment() and decrement()
Comments