SiteCrafting Blah Blah Blog

Jan. 4, 2008 at 3:21pm

Anonymous Recursion with JavaScript

A new way of solving an old problem

A nice feature of JavaScript is that functions are objects. As such, they do not need a name if they are used right away. But what if you need a short anonymous recursive function? arguments.callee becomes your new best friend.

Before I go into the details, let me start off by quickly explaining what I'm talking about. In JavaScript, you can define a function that without giving it a name or variable if it is to be used immediately, similar to numbers, strings or booleans. Because there is no name for your function it is considered anonymous. Recursion is where a function calls itself and is used a good deal in trees so this method applies well since the DOM is just a big tree.

But wait! How can you call a function if it has no name?

Simple! JavaScript 1.4 added a way to find out what function you are in (actually, 1.2, but it's done in a deprecated way). This is done with arguments.callee. This a local variable that is set once you start a function and allows you to throw arguments into it make a call to a function that has no name.

And this is useful?

Why yes, yes it is! Often when running Ajax queries, you assign an anonymous function to occur once the request is returned. Prototypes and other JavaScript frameworks also put you in a position of frequently using anonymous functions. I've found anonymous recursion handy when using timers and other events.

So, show us the example already!

The first example is a very simple recursive power function. It just takes the value of X to the power of Y. Yes, there is a function already to do this, and yes it is far more efficient, but this example does show a simple use of recursion.

The second example is a bad fade script. (A) It doesn't deal with IE opacity, and (B) it uses the $() function at each iteration. Nonetheless, I believe it shows a point when many developers wish they had direct access to the function for recursion.

Posted in Coding Techniques, Javascript by Paul Sayre

Comments (0)

Add your comment below


Remember me
Name: Email: URL: Comment: *   No HTML, http:// will auto-link
* required    Comment Guidelines