HTML DOM
HTML DOM console trace() Method
The console.trace() method prints a stack trace to the web console, showing the chain of function calls that led to the point where trace() was called. It is a powerful tool for understanding how a piece of code was reached.
Definition and Usage
console.trace() writes a stack trace to the console at the moment it runs. The trace lists the current function and each function that called it, all the way back up the call stack, so you can see exactly how execution arrived at that line.
You can pass an optional label or values that are printed above the trace. Like other console methods, it does not stop or alter your program's flow.
Syntax
console.trace(label)Example
Open the developer console (F12) and run this snippet. The console shows the call chain first -> second -> third.
function third() {
console.trace("Trace from third()");
}
function second() {
third();
}
function first() {
second();
}
first();More Examples
console.trace() is useful when a function is called from many places and you want to know which caller triggered it this time.
function save() {
console.trace("save() was called");
}
document.body.addEventListener("click", save);
save(); // direct call - the trace shows the differenceThe stack trace only appears in the developer console, not on the page. Expand the trace entry to click through to each function in the source.
Key Takeaways
- console.trace() prints the current call stack to the console.
- It shows every function that led to the current line.
- An optional label is printed above the trace.
- It is ideal for finding which caller triggered a function.
