JavaScript CallStack

It is often very useful to determine the call-stack when debugging client-side JavaScript code. Here is a simple solution populating the call stack into a string.

The sample code below has two components: travel up the call stack by accessing the caller of each function, and process the arguments of each entry in the stack. The getCallStack() function can be used in many contexts, including for instrumentation of event propagation.

JavaScript call stack retrieval function.

function getCallStack() {
var f = getCallStack, result = "Call stack:\n\n";
while ((f = f.caller) !== null) {
if (f.toString().match(/^function (\w+)\(/) != null)
result += f.toString().match(/^function (\w+)\(/)[1] + parseArguments(f.arguments) + "\n";
else result += 'anonymous' + parseArguments(f.arguments) + "\n";
}
return result;
}
function parseArguments(a) {
var result = [];
for (var i = 0; i < a.length; i++) {
if (typeof a[i] === 'string')
result.push("\"" + a[i] + "\"");
else result.push(a[i]);
}
return "(" + result.join(", ") + ")";
}

Leave a comment

Who's the Coach?

Ben Ruiz Oatts is the insightful mastermind behind this coaching platform. Focused on personal and professional development, Ben offers fantastic coaching programs that bring experience and expertise to life.

Get weekly insights

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.