May 24 2009

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