0

I had a little understanding of closure which, a function that can be stored as a variable (referred to as a "first-class function"), that has a special ability to access other variables local to the scope it was created in.

Somehow I had trouble how this code works, how does these independent functions messageForRahul/Greg gets executed inside the Inner function when they are not declared as a parameter?

var sendMessageTo = function (name) {

return function (message) {
    console.log ("Message for " + name + ": " + message);
}
};

var messageForRahul = sendMessageTo ("Rahul");
var messageForGreg = sendMessageTo ("Greg");


messageForRahul ("Hello, Rahul");
messageForGreg ("Hello, Greg");

1 Answers1

1

I'll try to give you the basic understanding.

var messageForRahul = sendMessageTo("Rahul");

You create a variable that invokes the function sendMessageTo and passes to it the parameter ("Rahul"). Than you do the same thing with this line of code: var messageForGreg = sendMessageTo("Greg");

Now you have two independent functions, which were running with different parameters.

The line messageForRahul("Hello, Rahul"); runs your inner function for function in which you passed the parameter ("Rahul").

As you can imagine, the last line of code runs your inner function for another function in which you passed the parameter ("Greg").

This code should help you to understand, what's happening. You can write the code this way:

    var sendMessageTo = function(name) {
      return function(message) {
        console.log("Message for " + name + ": " + message);
      }
    };
    sendMessageTo("Rahul")("Hello, Rahul");
    sendMessageTo("Greg")("Hello, Greg");

First you invoke the outer function sendMessageTo("Rahul"), and then the inner function ("Hello, Rahul").

Commercial Suicide
  • 14,875
  • 14
  • 62
  • 80