HTML DOM console.trace() Method


The HTML DOM console.trace() method is used to display the stack trace upto the point the console.trace() method has been called upon. It is basically used for displaying the code path i.e how the code ended up at that point.

Syntax

Following is the syntax for console.trace() method.

console.trace(label);

Here, label is an optional parameter of type string to specify the label for the code trace. This helps if there are multiple traces for different pieces of code.

Example

Let us look at an example for the console.trace() method −

<!DOCTYPE html>
<html>
<body>
<h1> console.trace() Method</h1>
<p>Click the below button…</p>
<button onclick="Function1()">Start Trace</button>
<script>
   function Function1(){
      Function2();
   }
   function Function2(){
      console.trace();
   }
</script>
<p>View the stack trace in the console after clicking the above button& </p>
</body>
</html>

Output

This will produce the following output −

On clicking the Start Trace button and viewing the output in console tab.

In the above example −

We have first created a button “Start Trace” that will execute the Function1() upon being clicked by the user.

<button onclick="Function1()">Start Trace</button>

The Function1() will execute Function2() and the Function2() will execute the console.stacktrace() method present inside it. It is a stack trace so it will follow the last-in first-out order. Since the console.trace method was called upon by the Function2() it will be the first to be popped.

The Function1() executed the Function2(), so it will be the second to be popped. Finally since Function1() was executed by “Start Trace” button on being clicked upon it will be the last one to be popped. It means it will be the reverse order in which they are being called upon −

<button onclick="Function1()">Start Trace</button>
function Function1(){
   Function2();
}
function Function2(){
   console.trace();
}
raja
Published on 08-Aug-2019 12:41:28
Advertisements