Passing Functions To Functions

Courtesy: hunlock.com

If we declare hello like a variable, it kind of makes sense that we can pass it like one as well.

var say = function(what) {
   what('say function');
}

var hello = function (who) {
   alert('Hello '+who);      // outputs "Hello say function"
}

say(hello);

So in Javascript a function can be passed just like an array or an object or any other variable. Or put another way, anything that can hold a value in javascript can hold a function.

There are two ways to use a function as an argument. You can pass a pointer to the function itself, or you can execute the function in the call and pass the return value of the function. The example above passed a pointer of the hello function to the variable what in the say function. what then became a pointer to hello.

If you’ve ever made an event in Javascript you’ve probably already used the pass as pointer concept because all the event handlers want a pointer to a function to call when they’re tripped. For instance…

function doSomething() {
   alert('you pushed my button!');
}

document.onclick=doSomething;

This example gives the function doSomething to the onclick event. Because we only used the function name and not doSomething(), onclick now has a pointer to doSomething. On the other-hand, if we were to use doSomething() things will still work out ok as long as doSomething() returns a pointer to a function…

function pushedMyButton() {
   alert('you pushed my button!');
}

function doSomething() {
   return pushedMyButton; // return a pointer to the pushedMyButton function
}

document.onclick=doSomething();

Now when the onclick event is set up, doSomething is executed because we appended parenthesis at the end. The parenthesis are an empty set — we’re not passing anything — but that’s ok, they tell javascript that we want to execute the function not pass a pointer to it. If doSomething() passes back a pointer to another function then the event will actually still work. In this example, doSomething returns a pointer to a function, which is the only thing onclick wants. onclick doesn’t care how it gets the pointer, it can take it either directly ( onclick=doSomething; ) , or as the result of a function returning one to it ( onclick=doSomething() ).

Just to recap; if you don’t follow a function name with argument parenthesis then you’re passing the function as a pointer. If you follow up a function name with argument parenthesis, even if they’re just an empty set — (), Javascript will execute the function and pass along the return value of the function. Keep that difference in mind, we’ll be coming back to it a little later.

var test = function () {
   return "This is a String";
}

var testCopy = test;      // testCopy is a pointer to the test function()
var testStr = test();     // testStr contians "This is a string"
var testing = testCopy(); // testing contains "This is a string"

Advertisements