Get the Stack Trace from an Error in JavaScript

avatar

Borislav Hadzhiev

Fri Dec 24 20212 min read

banner

Photo by Jonny Swales

Get the Stack Trace from an Error in JavaScript #

Use the console.trace() method to get the stack trace from an error. The console.trace() method outputs the stack trace and shows the call path taken to reach the point at which the method was called.

index.js
function outer() { function inner() { console.trace(); } inner(); } outer();

We defined a nested function in which we called the console.trace() method and invoked the outer function.

The method outputs the stack trace to the console if you're in the browser or the terminal if in Node.js.

stack trace output

The message shows the path taken to reach the point at which we called the console.trace() method.

The stack trace from the example shows that the inner function was called from the outer function, which was called from the global scope.

The message also shows the name of the file the functions are defined in.

The line numbers from the message mean:

  • the console.trace method was invoked in the index.js file on line 9.
  • the inner function called the console.trace method on line 9.
  • the outer function called the inner function in the index.js file on line 12.
  • the outer function was called in the global scope of the index.js file on line 15.

An alternative approach is to use the Error.stack property to get the stack trace from an error.

index.js
function outer() { function inner() { const err = new Error('Something went wrong'); console.log(err.stack); } inner(); } outer();
It should be noted that the stack property on the Error object is non-standard and is not on a standards track.

Here is the output from logging the stack property to the console.

error stack property

The stack property of the Error object shows a trace of which functions were called, in what order, in which file and on what line.

There is no standard formatting so the message will look different between different browsers.

The line numbers from the message mean:

  • the stack property on the Error object was logged on line 10 in the index.js file.

  • the error object was created on line 9 in the inner function.

  • the outer function called the inner function on line 13 in the index.js file.

  • the outer function was called on line 16 in the global scope of the index.js file.

Which approach you pick is a matter of personal preference. I'd use the console.trace method because it's standardized between browsers. If you use the stack property, your results may vary between browsers and some browsers might drop support for it or not implement it as it is a non-standard property.
Use the search field on my Home Page to filter through my more than 1,000 articles.