Course contentsShow
← Web Development
Lesson 2191 of 2,98240. Browser DevTools Deep DiveFree lesson

Console.trace() and Stack Traces

Output stack traces to understand function call chains and execution context.

Console.trace() and Stack Traces

You'll learn how to use console.trace() to visualize the complete chain of function calls that led to a specific point in your code.

What Is a Stack Trace?

A stack trace shows you the "breadcrumb trail" of function calls that got you to the current line of code. Think of it like checking your phone's location history to see every turn you took to reach your destination—except here, you're tracking how execution flowed through your functions.

When you call console.trace(), the browser outputs the entire call stack: which function called which, all the way back to the starting point. This is invaluable when debugging complex applications where functions call other functions several layers deep.

When to Use Console.trace()

Use console.trace() when:

  • You want to understand how a function got called
  • Multiple code paths lead to the same function, and you need to know which one executed
  • You're tracking down unexpected behavior deep in nested function calls

How It Works

Simply insert console.trace() at any point in your code:

function calculateTotal(items) {
  console.trace('calculateTotal called');
  return items.reduce((sum, item) => sum + item.price, 0);
}

function processOrder(order) {
  return calculateTotal(order.items);
}

function checkout(cart) {
  processOrder(cart);
}

checkout({ items: [{price: 10}, {price: 20}] });

The console will show:

  • calculateTotal (where trace was called)
  • processOrder (which called calculateTotal)
  • checkout (which called processOrder)
  • The global scope (which called checkout)

Key Takeaway: console.trace() reveals your function call chain, making it easy to understand execution context and debug complex code paths.