Saturday, January 2, 2010

The reason why Firebug's console.trace sometimes reports anonymous()

From Firebug's Console API:

Console.trace prints an interactive stack trace of JavaScript execution at the point where it is called.

Let's take the following code:

var f1 = function (a) {
    return f2(a + 1);
};
var f2 = function (a) {
    return f3(a + 1);
}
var f3 = function (a) {
    console.trace();
};

f1(5);

The console.trace in f3 prints out the following output in Firebug's Console:



As you can see from the above output, Firebug is reporting anonymous() for all the functions.

Why?

The reason for this is because I am using anonymous functions and for the JavaScript interpreter (and Firebug) f1, f2 and f3 are just variable names.

Now, let's change the above code to use named functions instead of anonymous functions:

function f1(a) {
    return f2(a + 1);
}

function f2(a) {
    return f3(a + 1);
}

function f3(a) {
    console.trace();
};

f1(5);

This is the output now: