How does JavaScript closures work?

JavaScript closures are not hard to understand If you already know the basic concepts of the JavaScript like scope of the variables, life time of the variables and the workflow of the your own program.

As my personal experienced the JavaScript closures is really hard to understand when we read about them but when we some example of it than we instantly get the light of it because it directly create the image in our mind.

What is closures ?

  • A closures is inner function that can access the the variables of its outer function.
  • Closures are a way to let function have persistent, private variables – that is variables that only function knows about it, and the function can store the state or information of the lastly executed task.

Which variables closures can access ?

  • It can access its own variables.
  • It can also access the variables of the its outer function.
  • It also can access the global variables.

Example:

function OuterFunction(name) {
    var msg = "Welcome, " + name + "!!!";
    var getWelcomeMessage = function () { return msg; } // This becomes the closure function
    return getWelcomeMessage;
}

var displayWelcomeMessage = OuterFunction("Mr. James Bond");
alert(displayWelcomeMessage());

If you are experienced developer of the JavaScript so you can notice that we are simply returned the reference of the inner function called getWelcomeMessage().

As per my experienced in JavaScript by using the closure function we are increasing the chances of the memory leakage. Let check some the code that will create the memory leakage.

function OuterFunction(name) {
    var msg = "Welcome, " + name + "!!!";
    var getWelcomeMessage = function () { return msg; } // This becomes the closure function
    return getWelcomeMessage;
}

var welcomeJamesBond = OuterFunction("Mr. James Bond");
alert(welcomeJamesBond());

var welcomeSmith = OuterFunction("Mr. Smith");
alert(welcomeSmith());

alert(welcomeJamesBond()); // still returns the old message

As you see that first we create the function for the welcomeJamesBond() and it return the correct message, after that we create the second closure function for the welcomeSmith() that also return the correct message and after that we call again the welcomeJamesBond() method, however it return the old message.

So its important to keep in mind while creating the closure function because we are just unintentionally creating the memory leakage. But by using this concepts we can able to implements some object oriented concepts.

function CeratePersonList(personList) {
    var welcomeMessage = "Welcome";

    var persons = [];
    for (i = 0; i < personList.length; i++) {
        persons.push(function () { alert(i + " " + welcomeMessage + " " + personList[i] + "!!!"); });
    }

    return persons;
}

function DisplayWelcomeMessages() {
    var person = CeratePersonList(["ABC", "XYZ", "AZY", "123"]);

    for (var j = 0; j < person.length; j++) {
        person[j]();
    }
}

DisplayWelcomeMessages();

When you run the above script you get the same output 4 times called “4 Welcome undefined!!!“. If in a simple language I say, the closure function uses the last modified value of the local variables so the when you call the closure function using the person[j]() at that time value of the i is the 4 but the in the array list of the personList there is not item in the index of the 4. So that’s why it display the same message for 4 time. Here single closure is create for local variables that’s why this problem is occurred.

So what is the solution of the above problem ? Simply We have to create one another independent function that will holds the data and return the desired output, So below is the solution..

function Message(i, welcomeMessage1, personName) {
    alert(i + " " + welcomeMessage1 + " " + personName);
}

function CeratePersonList(personList) {
    var welcomeMessage = "Welcome";

    var persons = [];
    for (i = 0; i < personList.length; i++) {
        persons.push(Message(i, welcomeMessage, personList[i]));
    }

    return persons;
}

function DisplayWelcomeMessages() {
    var person = CeratePersonList(["ABC", "XYZ", "AZY", "123"]);

    for (var j = 0; j < person.length; j++) {
        person[j]();
    }
}

DisplayWelcomeMessages();            

Now above code will gave you the desired output it will simply display the alert message with different different peoples name. Now below is another simple example of the JavaScript Closure function.

function Counter(defaultNumber) {
    var num = defaultNumber;
    return function (a) {
        num += a;
        return num;
    }
}

cnt1 = Counter(10);
alert(cnt1(1)); // alert with 11

cnt2 = Counter(0);
alert(cnt2(2)); // alert with 2

alert(cnt1(5)); // alert with 16

alert(cnt2(5)); // alert with 7

This examples shows that each call create the separate closure for the local variable, There is a closure for each call to function. In simple language and object oriented language Here we are creating the object of the Counter function, here Counter function works like the class.

However I realise that above examples of the Closures are may be difficult to understand to beginner of the JavaScript programmer. So for the simplicity I would like give one sort definition of it and its example.

Simple Definition: When you are creating the function within another function its called the closure.

Simple Example:

function DisplayGreetingMessage(FirstName, LastName) {
    var msg = "Welcome to ";
    function BuildGreetingMessage(anotherMsg) {
        return msg + anotherMsg + " " + FirstName + " " + LastName + ".";
    }
    return BuildGreetingMessage;
}

var user = DisplayGreetingMessage("James", "Bond");
alert(user("JavaScript Hive")); // Welcome to JavaScript Hive James Bond.

Above is the simplest example of the JavaScript Closures with maximum implements of its concepts.

Final Words:

  • Whenever we use the function inside the another function is called the closure.
  • When we use new Function() class to create function inside the function. It does not create the closure.
  • By creating the closure we are keeping the copy of the local variables of the function.
  • Closure have access to the outer function’s variable even after the outer function returns it pointer or value.

If you want to learn more about the functions and it’s declaration or the function expression click here.

Happy Coding!!!

🙂