Reputation: 36779
Recently I saw this piece of JavaScript code, but have been unable to understand what it is trying to do.
var f = function(a) {
return function() {
alert(a());
};
};
f(function() { return "Hello World"; })();
Please explain what this accomplishes!
Upvotes: 8
Views: 2756
Reputation: 103817
It's just a higher-level function, which in this case isn't really necessary.
f
is a function that takes another function (called a
), and returns a newly generated function that will evaluate a
and pop up an alert box showing the result.
So the bottom line calls f (passing in an anonymous function that prints "Hello World"), then immediately evaulates the anonymous function returned by f
- which will evaluate the argument passed in (which you can see returns "Hello World") and then pops up an alert box.
The code posted is functionally equivalent to
alert("Hello World");
but there's two extra elements that make it more complex:
But since neither of these benefits are actually used in the code snippet, I can see why you'd be confused.
Upvotes: 6
Reputation: 1800
It executes the function that f returns.
f returns a function that calls an alert that displays the output of the function you gave as parameter to f.
EDIT: Just substitute some parts to make it easier on the eye and you will see yourself:
var f = function(a) {
var output = a();
var alertCaller = function() {
alert(output);
};
return alertCaller;
};
var helloWorld = function() { return "Hello World"; }
var result = f(helloWorld); //f takes a function as argument
result(); //result must be a function
Upvotes: 9
Reputation: 118158
f
is assigned a function that takes a function as its argument, invokes it, and displays its return value in an alert
. Then f
is called with a function that returns the string "Hello World"
when its invoked, resulting in Hello World
being displayed in an alert.
Upvotes: 0
Reputation: 351566
This code creates a function generator. The first function (whose reference is stored in f
) accepts a reference to another function (a
). Then f
creates a function that closes over the parameter a
and returns a reference to the new function that will alert the return value of a's
invoked result.
Finally this mess is called with an inline function and its result is immediately invoked (with the trailing open and close parenthesis at the end).
Upvotes: 2
Reputation: 33867
It's a very complicated way to get an alert box to display "Hello world". Functions are first class items in javascript, and can be passed to and from other functions as parameters.
Upvotes: 3