What is console.trace in JavaScript?

With console.trace, we can print the stack trace of all function call to reach the console.trace statement. The stack trace will be printed in the console.

function first(){
  second();
}
function second() {
  console.trace("This line is called from");
}

function main(){
  first();
}

main();

// output in console  
VM43:5 This line is called from
second @ VM43:5
first @ VM43:2
main @ VM43:9
(anonymous) @ VM43:12

In the above code, we have the main function that will call the one function. This one function will then call the two function.

main — first — second

On the second function, we print the stack trace. The stack trace will print the function call path to reach the console.trace call.

Use case of console.trace

We can use console.trace in situations where we need to find out how a particular function is being executed.

Sometimes we bind the same method to a different event listener on that case. We can use this while debugging.


Passing Arguments to console.trace

console.trace accepts multiple arguments so that we can log data and stack traces in the same call.

For example, if we need to see the value of a variable along with the stack trace while debugging, then we can pass that variable to console.trace. console.trace will print along with stack trace.

function first(val){
  second(val);
}
function second(val) {
  console.trace("This value in variable val is ", val);
  return val; // this line will be executed as usual 
}

function main(val){
  first(val);
}

main(3);
main({name: "Educative"});

The above code will produce:

Free Resources