Printing JavaScript stack traces using console.trace

The console object in JavaScript has a lot more useful functions than the most frequently used console.log method. Debugging errors and finding execution flow can be a lot easier by making use of the console.trace method. It allows us to print the current stack trace where the method was called.

Usage

Writing console.trace() prints file names and line numbers of the call stack that exists when the method was invoked.

- Advertisement -
const stackTraceExample = () => {
  const nestedFunction = () => {
    console.trace();
  }

  nestedFunction();
}

stackTraceExample();

will print

nestedFunction @ VM56:3
stackTraceExample @ VM56:6
(anonymous) @ VM56:9

We can even pass arguments to the method:

const anotherExample = () => {
  console.trace('My log statement');
}

anotherExample();

/*
VM111:2 My log statement
anotherExample @ VM111:2
(anonymous) @ VM111:5
*/

Another thing to know as that the same trace is available on an error object as well.

const error = new Error('foo');
console.log(error.stack);

The links in the console are clickable and we can navigate to individual files if we wanted to read the source code. This makes debugging quicker and easier. If you have any questions, feel free to drop them as a comment below.

Recent Articles

Benefits Of Guest Blogging For SEO

Guest blogging entails the art of writing and publishing posts to be content for someone else. Guest blogging and posting on other...

Chrome devtools: Using logpoints for logging messages directly

When it comes to debugging JavaScript in Chrome devtools, there are two different camps: the console.log fans and the debugger/breakpoint maximalist. I...

How to prevent npm install for unsupported Node.js versions

npm configurations allow us to do quite a lot of nifty things. One of them is to allow the project to set...

How to terminate a process on a port using the command line

Zombie processes are usually a pain to figure out. More often than not, I end up googling about how to terminate a...

Detecting dark mode preference using JavaScript

As dark themes have become popular across the web and across operating systems, we might want to check the user's operating system...

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Hi there! Want some more knowledge?

Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out.

Hi there! Want some more knowledge?

Think that the knowledge shared is helpful? You might want to give our mailing list a try. We'll send you 2-4 emails a month, right when new posts come out.