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!
The purpose of the return statement in any language causes your function to exit and hand back value to its caller. The point of functions, in general, is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.
A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.
Functions are the same data as numbers or strings, so functions can be passed to other functions as arguments, as well as returned from functions. We can even define a function inside another function and return it outside.
No; Javascript functions are not required to return a value. If you call a function that doesn't return a value, you'll get undefined as the return value.
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
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