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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With