Recursive, Anonymous, and Simple functions in Javascript

Functions are objects. This makes recursion short and sweet in javascript using anonymous functions.
In your html, php, or asp file try this out.

<input type=’button’ id=’myButton’ value=”5″>

<script type=’text/javascript’>
var myButton = document.getElementById(“myButton”);
var i=myButton.value;

myButton.onclick = function() {
if(i==0)
{
alert(“DONE”);
myButton.value = i;
return i;
}
alert(i);
return arguments.callee(–i);
};

</script>

I attached the anonymous function onto the onclick event for the button that was created right above the javascript. When that button is clicked the anonymous function will call itself and decrement ‘i’ until it is zero. When ‘i’ becomes zero the value of the button is set to 0 and the function returns. Nice and simple.

The only possible confusing thing here is the arguments.callee line. Remember I said that functions are objects? The arguments.callee actually calls itself. We need this because we don’t have a handle for the anonymous function. The arguments object is a local variable that all functions have. It can be used like an array to access the values passed to the function. It also holds ‘callee’, ‘caller’, and ‘length’. Since the callee is the function itself then caller is obviously the function that called it and length is the number of arguments passed to the function.

Share

2 Responses to “Recursive, Anonymous, and Simple functions in Javascript”

  • Andrew Says:

    Alternatively you could man up and use the Y Combinator (see http://javascript.crockford.com/little.html) like a real functional programmer:

    function Y(le) {
    return (function (f) {
    return f(f);
    }(function (f) {
    return le(function (x) {
    return f(f)(x);
    });
    }));
    }

    myButton.onclick = Y(function(f) {
    if(i==0)
    {
    alert(”DONE”);
    myButton.value = i;
    return i;
    }
    alert(i);
    return f(–i);
    });

  • Zach Says:

    Don’t use arguments.callee, it’s deprecated! If you need to reference your function in the function body, it’s obvious you should be using a named function, not an anonymous one. Specifying a name will create a local variable in the functions scope of that name. Use that instead.