Header Ads Widget

Practical Usage of Closure in JavaScript


Closure is a very important concept that every JavaScript developer should understand. In my earlier post, I discussed what is closure and then, some examples to understand this concept. I highly recommend you go through that post and video before going into the details of this post.


Note - I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate.

This post will cover some of the practical use of closures:

Private variables and methods

Private variables and methods can be implemented using closures.

var doOperation = function (value) {
//Private Variable
var initialValue = value;

//Private Function
var printValue = function () {
console.log("Inside printValue: " + initialValue);
};

return {
getValue: function () {
printValue();
},
incValue: function (value) {
initialValue += value;
console.log(initialValue);
},
decValue: function (value) {
initialValue -= value;
console.log(initialValue);
},
};
};

var Val = doOperation(100);

Val.incValue(50);
Val.decValue(25);
Val.incValue(500);
Val.getValue();

In the above example, the doOperation is returning an object with three methods getValue(), incValue() and decValue(). All of these three methods are basically accessing the private variable initialValue and private function printValue. Code outside its scope cannot directly access this variable, if we try to do that we will get an undefined value. This is the way we can use closure to implement the object-oriented concepts.

Function factories

We can use closure to create function factories i.e. use the outer function as a factory for creating functions with similar functionalities. Below is one example -

function greeting(greetingMsg) {
return function (toWhome) {
console.log(greetingMsg + ", " + toWhome);
};
}

var morning = greeting("Good Morning");
var evening = greeting("Good Evening");
var night = greeting("Good Night");

morning("James Bond");
evening("Shane Warne");
night("Brain Lara");

As you can see I am returning a function that is printing a string containing the parameters from the outer function as well as inner function. This way we can keep our JavaScript DRY. 

These two are very common usage of closure. Please let me know in comments if you have any other examples.


Post a Comment

0 Comments