Menu
A JavaScript Function That Returns a Function

A function is a block of code that returns a value. When your code calls a function, you may pass a value or values to the function. These values are called arguments or parameters. When execution of the code in a function comes to a return statement, the thread of execution will return to the code that invoked the function. Functions often return a value. The return value is returned back to the code that invoked the function.

function myMultiply(p1, p2)
{
   return p1 * p2;
}

The example above defines a function named myMultiply that takes two parameters, p1 and p2, and returns the product of p1 and p2.

A function's return statement can also return a function. The example below shows the use of the return statement to return a function.

function myWorker()
{
   return function myMultiply(p1, p2) { return p1 * p2; };
}

var func = myWorker();
var x = func(2, 5);
document.write(x);

When myWorker is called, the function myMultiply is returned and placed in a variable named func, then func is passed two parameters and it returns the product of the two parameters to the variable x.

These are sometimes called higher-order functions. A higher-order function is a function that returns a function, or a function that can take another function as an argument. Is there any practical use for a function that returns a function? Not really, but they can be used to compensate for poor programming practices. The example below shows a poor programming practice.

function myWorker()
{
   a = 2;
   var b = 5;
}

myWorker();

document.write(a);
document.write(b);

The function myWorker declares two variables, a and b. Without the var statement, a implicitly creates a global variable. With the var statement, b's visibility is constrained to within the function myWorker. The document.write(a) statement will write "2". The document.write(b) statement will not write because b is not defined outside myWorker.

Another poor programming practice a function that returns a function compensates for is weak global variable naming. All JavaScript code in a document, whether in a local script block, or included from an external file, share the same global namespace. So if you declare a global variable named count, it will collide with any other global variables named count even if they where included as external advertising or affiliate code.

The solution is, of course, to use variable names that are not likely to be commonly used. This can be achieved by attaching a prefix to your global variable names, e,g. ns_xtjpr_count. But you can also solve the problem by wrapping all your variables in functions that return functions that access the outer functions local variable(s).

The example below defines a function counterCreator() that returns the function incCount() which increments the variable count in it's outer function.

function counterCreator()
{
   var count = 0;
   return function incCount() { return ++count; };
}

var counter1 = counterCreator();

alert(counter1());

alert(counter1());

alert(counter1);

alert(count);

The statement below the function declaration places code for incCount() function in variable counter1. The following alert function executes incCount(), incrementing counter1 to 1. The next alert function executes incCount(), incrementing counter1 to 2. The next alert function does not increment, or even display counter1 because the variable count is local to counterCreator() and is not visible globally. same with the last alert function.

In the next example, we defines the same function counterCreator(), but this time we place code for incCount() function in variable counterA and in variable counterB.

function counterCreator()
{
    var count = 0;
    return function incCounter() { return ++count; };
}

var counterA = counterCreator();
var counterB = counterCreator();

alert(counterA());

alert(counterA());

alert(counterB());

alert(counterA());

The first alert function calls the incCounter() function in variable counterA incrementing counterA to 1. The second alert function calls the incCounter() function in variable counterA incrementing counterA to 2.

The next alert function calls the incCounter() function in variable counterB incrementing counterB to 1. We prove the two counters are independant when next alert function calls the incCounter() function in variable counterA producing an output of 3.

The above demonstrates that each counter has its own local namespace and so is able to maintain its own independent count variable, so in effect by creating a function that returns a function you are creating local scoped variable that behaves like a global variable but without the possible namespace collision.

However, as in everything in life, there are trade-offs. Using this method to avoid global variables complicates the code and requires the processor to perform stack operations. In other words every time you execute a function the processor has to save the program pointer so it knows where to return to when the function exits. Here we have two unnecessary function calls, reducing program speed. It's more efficient to just use more creative global variable names.


Article resources: [javascriptworkshop.com domain for sale] and adripofjavascript.com


Learn more at amazon.com

More Java Script Code:
• Java Script Code to Calculate Speed / Distance of Falling Object
• Java Script Trim Function
• Code to Fade Between Two different Pictures
• Creating Basic Java Script Functions
• Slide Show with Different Size Images
• Easy JavaScript FileReader Code
• Easy JavaScript Form Design
• Regular Expressions Boundaries
• Java Script Code to Re-arrange Items in a Select List
• How to Shuffle the Deck With Java Script