Call traces with console.trace
Learn to see a function's call stack with console.trace.
Call traces with console.trace
console.trace() prints the call stack from the point where it is called. The call stack shows which function called which up to that point: the innermost call appears at the top and the outermost call at the bottom.
This answers the question "which chain of functions reached this line?". It is very useful when tracing a bug or an unexpected call.
How to read the call stack
The call stack is listed from the innermost call to the outermost. For example, if function a calls b, b calls c, and c contains console.trace(), the stack appears in the order c → b → a.
The top line is the function that contains console.trace. As you go down you see the calling functions. This order shows the path the bug took to appear.
Exercise See the call trace with console.trace
Define a function called greet. Inside it, call console.trace("greet called"). Then call the greet() function. This way you see the call stack in the console.
Show example solution
function greet() {
console.trace("greet called");
}
greet();
Test yourself
-
What does console.trace() print?
- Only the word 'trace'
- The call stack
- The value of every variable
- The running time of the code
Show answer
The call stack — Correct. console.trace shows the call stack.
-
Complete the console.trace call
function helper() { console.____(); }Show answer
function helper() { console.trace(); } -
Match the call stack
- Innermost call
- Top line of the stack
- Outermost call
- Bottom line of the stack
- console.trace()
- Prints the call chain
- Call stack
- Which function called which