Course contentsShow
← JavaScript
Lesson 1486 of 2,72332. JavaScript in the BrowserFree lesson

Console.trace for Stack Traces

Print stack traces to understand the call path that led to a particular point in your code.

Console.trace for Stack Traces

You'll learn how to use console.trace() to print the call stack and see exactly which functions led to the current execution point.

What is Console.trace?

When debugging complex code, you often need to know how you got to a particular line—what sequence of function calls led you there. console.trace() prints a stack trace showing the entire call path, like breadcrumbs leading back to where your code started.

Think of it like a detective retracing steps: "The error happened here, but who called this function? And who called that function?" Console.trace answers all those questions at once.

How to Use Console.trace

Simply call console.trace() (optionally with a label) anywhere in your code:

function firstFunction() {
  secondFunction();
}

function secondFunction() {
  thirdFunction();
}

function thirdFunction() {
  console.trace('How did we get here?');
}

firstFunction();

Output (in the browser console):

How did we get here?
thirdFunction @ script.js:10
secondFunction @ script.js:6
firstFunction @ script.js:2
(anonymous) @ script.js:13

This shows you the complete call stack: thirdFunction was called by secondFunction, which was called by firstFunction, which was called at the global level.

When to Use It

Use console.trace() when:

  • Debugging unexpected function calls
  • Understanding complex call chains
  • Investigating "how did this code execute?"
  • Tracking down who's calling a particular function

Unlike console.log(), which just shows data, console.trace() shows context—the journey your code took to reach that point.

Key Takeaway: Use console.trace() to print the call stack and visualize the sequence of function calls that led to the current execution point—invaluable for debugging complex flows.