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

ilgaar picture ilgaar · Jun 30, 2013 · Viewed 12.7k times · Source

Is it possible to find out where a function is called from? If yes, then how to detect, if a function is called from a global scope, from another function, or perhaps from a browser console?

Take a look at the following example:

<script>
    function myFunc1() {
        // some code
        myFunc2(); // I was called from myFunc1()
    }
    function myFunc2() {
        var callerName = new String;
        callerName = arguments.callee.caller.name;
        // some code
        alert('I was called from ' + callerName + ' function');
    }
    myFunc2(); // I was called from global scope
</script>

I know that this line callerName = arguments.callee.caller.name;in the example above, would give me caller function's name. But I don't know how to detect if a function was called from a global scope. For instance if I change myFunc2() and add an if else statement to check if arguments.callee.caller.name returns an undefined value, knowing that this will happen, when a function is called from a global scope:

myFunc2() {
var callerName = new String;
callerName = arguments.callee.caller.name;
    if(callerName == undefined) {
        alert('I was called from global scope');
    } else {
        alert('I was called from ' + callerName + ' function');
    }
}

However, this will not work if myFunc2() is called from a global scope and callerName = arguments.callee.caller.name; will cause JavaScript to throw the following error:

TypeError: 'null' is not an object (evaluating 'arguments.callee.caller.name')

So I am back to square one, and the question still remains:

  • How to detect if a function is called from a global scope?
  • If it's called from a global scope, is it from a browser console?

Answer

Gene Parcellano picture Gene Parcellano · Apr 7, 2017

In Chrome, you can use:

console.trace();

Just add that line in your function, I usually place it as the first line. If you view the console you'll see the name of your function, and below that line you'll see where it's being called from.