Functions that Return Functions

A function always returns a value, and if it doesn't explicitly return, then it implicitly returns undefined. A function can return only one value and this value could be another function.

function a() {
    alert('A!');
    return function() {
        alert('B!');
    };
}

In this example the function a() executes (says A!) and returns another function and executes (says B!). You can assign the return value to a variable and then use this variable as a normal function.

var newFunc = a();

newFunc();

Here the first line will alert A! and the second will alert B!.

To execute the returned function immediately, without assigning it to a new variable, you can use another set of parentheses. The end result will be the same.

a()();
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +