JavaScript StackTrace With The console Object

Error handling and debugging had been made difficult in JavaScript because the lack of tools and the language itself. Unlike Java, that has a strong type and hierarchy of exception classes, JavaScript didn’t even have a direct approach to print the execution stack trace. For years I used a workaround to navigate around stack trace of a method call in JavaScript by using the Function arguments property. In JavaScript, all functions have an arguments property defined. The arguments property is available even if the function is defined with no explicit function parameters. The function arguments property behaves like an array and you can iterate through the argument parameters used to call the function but it also has a reference to the caller via the arguments.callee property. The arguments.callee property references the currently executing function itself, which has a caller property to that of the previous function call in the execution stack.

function basicFunction() {
   var isTrue = arguments.callee == basicFunction; // true
   var callingFunction = arguments.callee.caller; 
}

In the above code, the callingFunction variable holds a reference to the Function object that called the basicFunction.

The caller property returns a Function object or null, so you can chain these until you get to the root of the call stack. You can iterate through a call stack in JavaScript with code similar to the following.

function basicFuction() {
   var caller = arguments.callee.caller;
   while(caller != null) {
      console.log(caller);
      caller = caller.caller;
   }
}

Unfortunately, there is no clean way to get the function name out of the Function object returned by the caller property. This is made slightly more difficult because somethings functions don’t have names if they are created anonymously. If you print or log a Function object, it displays the function definition in its entirety.

Fortunately, the JavaScript console object provides a trace function that will log to the web console the JavaScript stack trace.

function basicFunction() {
   console.trace();
}

If the above function is invoked from an on click event, the whole JavaScript track trace from the on click to the basicFunction function is logged out in the web console. In addition to the function names, the web console in Safari, Chrome, and Firefox have a link to navigate to the exact location your web application where the functions were called.