user3763682
user3763682

Reputation: 441

How do I call the returned inner function of another function?

I'm trying to solve a problem from an online tutorial. Consider the following function:

var badFunction = function() {
  return function() {
    return "veryBad"
  }
}

Here, badFunction returns a function that returns "veryBad". I want to store "veryBad" inside theBad. How can I call the returned inner function? This answer isn't acceptable:

var theBad = "veryBad!";

Neither is this:

var theBad = badFunction(); 
theBad();

Although both of those work. So how do I call the inner function?

Upvotes: 4

Views: 58

Answers (1)

Andrew Li
Andrew Li

Reputation: 57964

Just call the return value:

var theBad = badFunction()();

This will first call the function badFunction, then after the function finishes, it will then call the returned function. The evaluation looks something like this:

badFunction()();
^^^^^^^^^^^^^
Step 1, calls badFunction

Then, once badFunction is called, it returns an anonymous function expression:

(function() { // <-- This is the return value of badFunction
  return "veryBad"
})();
  ^^
  Step 2, call the returned function expression for "veryBad"

Of course, you could store the returned function in an intermediate variable, then call that:

var veryBadFunc = badFunction();
var theBad = veryBadFunc();

This would store the returned function in veryBadFunc which you could call later and store in theBad. This is exactly what you've done in your last try. The catch is that you have to do something with the return value, such as store it in a variable for later use.

Upvotes: 10

Related Questions