How to de-anonymize your anonymous functions

First of all, de-anonymized functions are called named functions and they look a lot like “regular” functions (in fact, they are).

Why should I de-anonymize?

For debugging. Instead of having a stack trace filled with ?() (representing an anonymous function), it is nicely printed and easier to follow.

For self-reference. Example, when you want an anonymous function to recall itself recursively, you would have to call arguments.callee. It’s odd and it’s deprecated anyway (people pointed to me that it’s not really deprecated but it throws an error in ECMAScript 5 strict).

Stack trace of anonymous functions…

If you run this in your firebug console (every javascripter should have firebug).

You get a stack trace that looks like this :
func()
func()
func()

… versus stack trace of named functions

You get a stack trace that looks like this :
f1()
f2()
f3()

As you can see, it’s a lot easier to debug and to understand who’s calling who.

Warning : There’s a bug in IE with named functions.

Recursive anonymous function

Let’s create a recursive anonymous function that counts to 10.

And let’s create it but using a named function.

Once again, the code is much clearer and it’s not using a deprecated element.

A note about closures to advanced javascripters

I just wanted to say that in the last example, you could have written this :

As you can see at line 4, I call the count function which is not the name of the function but the variable to which the function is assigned. It works, but it may not be the best thing to do. You can learn more about closure on that previous post and I’ll write more about it.

  • In your first example under the "Recursive anonymous function" you do not need to use callee at all. Due to Lexical Scoping, you have access to the count variable from within the function.

    var count = function(i) {
    if (i <= 10) {
    console.log(i);
    count(i+1);
    }
    }

    count(1);
  • fearphage
    Your solution leaks memory in IE.

    See here: http://yura.thinkweb2.com/named-function-expressions/#jscript-bugs
  • WalterGR
    (BTW, you might want to replace the code comment "// this is deprecated" with "// this throws an error" or something...)
  • done. thanks!
  • BigAB
    Though not technically deprecated in ECMAscript 5 access to arguments.caller and arguments.callee now throw an exception in strict mode.

    So splitting heirs regardless, you may want to avoid using it.
blog comments powered by Disqus