user3763682 user3763682 - 5 months ago 33
Javascript Question

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"

returns a function that returns
. I want to store
. How can I call the returned inner function? This answer isn't acceptable:

var theBad = "veryBad!";

Neither is this:

var theBad = badFunction();

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

Answer Source

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:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download