Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "return function() { ... }" do in JavaScript?

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!

like image 998
Rakesh Juyal Avatar asked Oct 19 '09 14:10

Rakesh Juyal


People also ask

What is the purpose of return?

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.

What is function () () in JavaScript?

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.

Can a function return a function JavaScript?

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.

Do you need return in JavaScript function?

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.


1 Answers

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
like image 139
moxn Avatar answered Sep 20 '22 00:09

moxn