How to find out where a function is called in JavaScript?

Estimated read time 1 min read

You can find out where a function is called in JavaScript by using the Error.stack property. The Error.stack property returns a string representing the stack trace of the error that caused the function to be called.

Here’s an example:

function getCaller() {
  try {
    throw new Error();
  } catch (error) {
    let stack = error.stack.split('\n')[3];
    return stack.substring(stack.indexOf('at ') + 3, stack.length);
  }
}

function firstFunction() {
  console.log('Called from: ' + getCaller());
  secondFunction();
}

function secondFunction() {
  console.log('Called from: ' + getCaller());
}

firstFunction();

In this example, we create a helper function getCaller that throws an error and captures its stack trace using the Error.stack property. We split the stack trace into an array of strings using the split() method, and then we extract the third line, which represents the function call that led to the current function. Finally, we return the string representation of the function call.

When we call the firstFunction, it logs the function call that led to it being called. When the secondFunction is called, it also logs the function call that led to it being called. In this way, you can trace the flow of function calls and determine where each function is called from.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply