Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 204
user3763682 Avatar asked Dec 23 '22 14:12

user3763682


1 Answers

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.

like image 59
Andrew Li Avatar answered Dec 28 '22 10:12

Andrew Li