63

How do I print a stack trace from JavaScript?

The answer How can I get a Javascript stack trace when I throw an exception? deals with throwing an exception, but I need to print stack traces to debug a memory leak.

Basically I've got the same question as Get current stack trace in Java but for JavaScript.

And How to print a stack trace in Node.js? is similar but it's Node.js and I want to know for JavaScript, more generally speaking, if it's different.

Stijn de Witt
  • 40,192
  • 13
  • 79
  • 80
Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113
  • 2
    Did you see the `stackTrace` function in the accepted answer? It boils down to `var e = new Error(); console.log(e.stack)` – Mike Cluck Apr 05 '17 at 16:39
  • Thanks Mike, but I wanted a page with a simple, direct answer on stackoverflow that google would index for the query "JavaScript print stack trace". – Michael Osofsky Apr 05 '17 at 16:41
  • 1
    But it's still a duplicate question, right? Couldn't you have posted your answer here as an answer to that question? Googling "JavaScript print stack trace" brings up the previous question as the first result, even when I go outside of my "Google bubble." – Mike Cluck Apr 05 '17 at 16:43
  • 2
    Mike, that question had to do with printing a stack trace when an exception occurred. My question has no connection to exceptions. The context is different. – Michael Osofsky Apr 05 '17 at 17:36
  • Debatable. The question was phrased in that way but most of the answers are generalized in such a way that you can get the stack trace without error handling. Regardless, I won't mark it as a duplicate because I don't want to be the sole-source-of-truth in this case since there is an argument against it. I'm just going to say I wouldn't be surprised if someone else decided to flag it as a duplicate. – Mike Cluck Apr 05 '17 at 17:43
  • Possible duplicate of [While debugging javascript, is there a way to alert current call stack?](https://stackoverflow.com/questions/2060272/while-debugging-javascript-is-there-a-way-to-alert-current-call-stack) – Kevin Aug 14 '17 at 22:30

3 Answers3

102

This line of code gets a stack trace and prints it:

console.trace();

Source: https://developer.mozilla.org/en-US/docs/Web/API/Console/trace

Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113
  • 1
    the console API was formally adopted almost 10 years ago - any JS engine that still doesn't support it can safely be ignored when it comes to questions like this: `console.trace()` is the default correct answer in absence of additional details along the lines of "how do I do X in this highly niche, super-legacy JS engine". – Mike 'Pomax' Kamermans Jul 31 '19 at 19:31
  • 9
    IMHO, this answer does not actually answer the question. The question is **Get** current stack trace, not **Print** current stack trace. Printing the stack trace is easy, it's getting it that's hard. I want to know the answer to `var currentStackTrace = /* what code here ? */` – Stijn de Witt Nov 26 '20 at 13:56
  • 1
    @StijndeWitt you could try parsing the `stack` field on `Error`, for example `var currentStackTrace = Error().stack.substring(6).split(" at ")` sets `currentStackTrace` to an array of strings where each string is a line in the stack. – Michael Osofsky Dec 01 '20 at 20:48
  • 1
    @MichaelOsofsky Yes, but I am talking about the fact that this accepted answer does not actually answer the question. As it stands, either the question title should change to "Print current stack trace in Javascript", or the accepted answer should change to [the one from SYOB SYOT](https://stackoverflow.com/a/57238353/286685) and we should remove the `print()` call from that. – Stijn de Witt Dec 05 '20 at 20:30
  • @MichaelOsofsky Maybe I should just change it already right :) – Stijn de Witt Dec 05 '20 at 20:31
  • 1
    `Error().stack` is the better answer because it's more general. It lets you do everything this answer does and more. – beauxq Jun 19 '22 at 21:57
59

You can get stack trace by creating error and printing its stack property.

var stackTrace = Error().stack;
print(stackTrace); // if print is available
console.log(stackTrace); // if console.log is available
alert(stackTrace); // ditto
var xhr = new XMLHttpRequest(); xhr.open(...); xhr.send(stackTrace); // submit to server
// or do whatever else with the variable

This unlike console.trace() works in all cases, even if console class is not available in your environment. (Of course, if print is not available, you can use console.log or any other function for printing which you have in your environment).

Mr. TA
  • 5,230
  • 1
  • 28
  • 35
SYOB SYOT
  • 900
  • 10
  • 14
  • 1
    Node.js does not have `print`, so your code doesn't work in the context of the question, whereas `console.trace()` has worked in Node.js since the very first release. – Mike 'Pomax' Kamermans Jul 31 '19 at 19:36
  • 4
    ```print``` is beside point here. It is just an example. ```Error().stack``` is important part. Beside, question asker has stated in his question that he wants more general than node.js answer. So context is not limited to node.js. More generally than node.js you do it by ```Error().stack``` and printing its output with whatever function you have available. ```Error().stack``` will work in any JavaScript version, while ```console.trace()``` will not. Plus, you can make ```print``` work in node.js if you do: ```print=console.log```. – SYOB SYOT Jul 31 '19 at 19:52
  • 2
    That last sentence along is the entire reason this is a bad answer: _everything_ that supports ES5 or above supports `console.trace()`, whereas your answer shows code that won't work in any browser, nor in Node.js - if you want to mention `new Error().stack` then by all means add that as second part to your answer. As it stands, your answer as posted does not work in any common JS engine, and as such [is a bad answer](https://meta.stackexchange.com/questions/7656/how-do-i-write-a-good-answer-to-a-question). Remember why SO exists in the first place: if the answer has code that code should work – Mike 'Pomax' Kamermans Jul 31 '19 at 20:12
  • 1
    Thank you for this response. It totally worked for me!! – Thomas Calhoun Jr. Dec 31 '19 at 02:25
  • 1
    this is best. thank you. without new is really good. – defend orca Oct 24 '20 at 16:10
  • 3
    @Mike'Pomax'Kamermans you are being entirely unreasonable here. Everybody, literally any programmer, can look at that answer (as it was before I edited it for clarity) and understand that `print` isn't important. Actually, this answer is better than the accepted one, because `console.trace()` can ONLY output it to the console, whereas `Error().stack` gives you options - submit to server, etc. – Mr. TA Feb 23 '21 at 20:33
6

The documentation says it could be done in the following way:

const targetObject = {};
Error.captureStackTrace(targetObject);
targetObject.stack;  // Similar to `new Error().stack`

This code snippet creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

dmytrops
  • 496
  • 7
  • 11