[javascript] How do you find out the caller function in JavaScript?

function main()
{
   Hello();
}

function Hello()
{
  // How do you find out the caller function is 'main'?
}

Is there a way to find out the call stack?

This question is related to javascript callstack

The answer is


Just want to let you know that on PhoneGap/Android the name doesnt seem to be working. But arguments.callee.caller.toString() will do the trick.


In both ES6 and Strict mode, use the following to get the Caller function

console.log((new Error()).stack.split("\n")[2].trim().split(" ")[1])

Please note that, the above line will throw an exception, if there is no caller or no previous stack. Use accordingly.

To get callee (the current function name), use:

console.log((new Error()).stack.split("\n")[1].trim().split(" ")[1]) 

Note you can't use Function.caller in Node.js, use caller-id package instead. For example:

var callerId = require('caller-id');

function foo() {
    bar();
}
function bar() {
    var caller = callerId.getData();
    /*
    caller = {
        typeName: 'Object',
        functionName: 'foo',
        filePath: '/path/of/this/file.js',
        lineNumber: 5,
        topLevelFlag: true,
        nativeFlag: false,
        evalFlag: false
    }
    */
}

If you are not going to run it in IE < 11 then console.trace() would suit.

function main() {
    Hello();
}

function Hello() {
    console.trace()
}

main()
// Hello @ VM261:9
// main @ VM261:4

I usually use (new Error()).stack in Chrome. The nice thing is that this also gives you the line numbers where the caller called the function. The downside is that it limits the length of the stack to 10, which is why I came to this page in the first place.

(I'm using this to collect callstacks in a low-level constructor during execution, to view and debug later, so setting a breakpoint isn't of use since it will be hit thousands of times)


I think the following code piece may be helpful:

window.fnPureLog = function(sStatement, anyVariable) {
    if (arguments.length < 1) { 
        throw new Error('Arguments sStatement and anyVariable are expected'); 
    }
    if (typeof sStatement !== 'string') { 
        throw new Error('The type of sStatement is not match, please use string');
    }
    var oCallStackTrack = new Error();
    console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
}

Execute the code:

window.fnPureLog = function(sStatement, anyVariable) {
    if (arguments.length < 1) { 
        throw new Error('Arguments sStatement and anyVariable are expected'); 
    }
    if (typeof sStatement !== 'string') { 
        throw new Error('The type of sStatement is not match, please use string');
    }
    var oCallStackTrack = new Error();
    console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
}

function fnBsnCallStack1() {
    fnPureLog('Stock Count', 100)
}

function fnBsnCallStack2() {
    fnBsnCallStack1()
}

fnBsnCallStack2();

The log looks like this:

Call Stack:
    at window.fnPureLog (<anonymous>:8:27)
    at fnBsnCallStack1 (<anonymous>:13:5)
    at fnBsnCallStack2 (<anonymous>:17:5)
    at <anonymous>:20:1 
Stock Count: 100

function Hello() {
    alert(Hello.caller);
}

It's safer to use *arguments.callee.caller since arguments.caller is deprecated...


If you really need the functionality for some reason and want it to be cross-browser compatible and not worry for strict stuff and be forward compatible then pass a this reference:

function main()
{
   Hello(this);
}

function Hello(caller)
{
    // caller will be the object that called Hello. boom like that... 
    // you can add an undefined check code if the function Hello 
    // will be called without parameters from somewhere else
}

To recap (and make it clearer) ...

this code:

function Hello() {
    alert("caller is " + arguments.callee.caller.toString());
}

is equivalent to this:

function Hello() {
    alert("caller is " + Hello.caller.toString());
}

Clearly the first bit is more portable, since you can change the name of the function, say from "Hello" to "Ciao", and still get the whole thing to work.

In the latter, in case you decide to refactor the name of the invoked function (Hello), you would have to change all its occurrences :(


Just want to let you know that on PhoneGap/Android the name doesnt seem to be working. But arguments.callee.caller.toString() will do the trick.


Try accessing this:

arguments.callee.caller.name

function Hello() {
    alert(Hello.caller);
}

If you really need the functionality for some reason and want it to be cross-browser compatible and not worry for strict stuff and be forward compatible then pass a this reference:

function main()
{
   Hello(this);
}

function Hello(caller)
{
    // caller will be the object that called Hello. boom like that... 
    // you can add an undefined check code if the function Hello 
    // will be called without parameters from somewhere else
}

here is a function to get full stacktrace:

function stacktrace() {
var f = stacktrace;
var stack = 'Stack trace:';
while (f) {
  stack += '\n' + f.name;
  f = f.caller;
}
return stack;
}

Here, everything but the functionname is stripped from caller.toString(), with RegExp.

<!DOCTYPE html>
<meta charset="UTF-8">
<title>Show the callers name</title><!-- This validates as html5! -->
<script>
main();
function main() { Hello(); }
function Hello(){
  var name = Hello.caller.toString().replace(/\s\([^#]+$|^[^\s]+\s/g,'');
  name = name.replace(/\s/g,'');
  if ( typeof window[name] !== 'function' )
    alert ("sorry, the type of "+name+" is "+ typeof window[name]);
  else
    alert ("The name of the "+typeof window[name]+" that called is "+name);
}
</script>

You can get the full stacktrace:

arguments.callee.caller
arguments.callee.caller.caller
arguments.callee.caller.caller.caller

Until caller is null.

Note: it cause an infinite loop on recursive functions.


Looks like this is quite a solved question but I recently found out that callee is not allowed in 'strict mode' so for my own use I wrote a class that will get the path from where it is called. It's part of a small helper lib and if you want to use the code standalone change the offset used to return the stack trace of the caller (use 1 instead of 2)

function ScriptPath() {
  var scriptPath = '';
  try {
    //Throw an error to generate a stack trace
    throw new Error();
  }
  catch(e) {
    //Split the stack trace into each line
    var stackLines = e.stack.split('\n');
    var callerIndex = 0;
    //Now walk though each line until we find a path reference
    for(var i in stackLines){
      if(!stackLines[i].match(/http[s]?:\/\//)) continue;
      //We skipped all the lines with out an http so we now have a script reference
      //This one is the class constructor, the next is the getScriptPath() call
      //The one after that is the user code requesting the path info (so offset by 2)
      callerIndex = Number(i) + 2;
      break;
    }
    //Now parse the string for each section we want to return
    pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
  }

  this.fullPath = function() {
    return pathParts[1];
  };

  this.path = function() {
    return pathParts[2];
  };

  this.file = function() {
    return pathParts[3];
  };

  this.fileNoExt = function() {
    var parts = this.file().split('.');
    parts.length = parts.length != 1 ? parts.length - 1 : 1;
    return parts.join('.');
  };
}

StackTrace

You can find the entire stack trace using browser specific code. The good thing is someone already made it; here is the project code on GitHub.

But not all the news is good:

  1. It is really slow to get the stack trace so be careful (read this for more).

  2. You will need to define function names for the stack trace to be legible. Because if you have code like this:

    var Klass = function kls() {
       this.Hello = function() { alert(printStackTrace().join('\n\n')); };
    }
    new Klass().Hello();
    

    Google Chrome will alert ... kls.Hello ( ... but most browsers will expect a function name just after the keyword function and will treat it as an anonymous function. An not even Chrome will be able to use the Klass name if you don't give the name kls to the function.

    And by the way, you can pass to the function printStackTrace the option {guess: true} but I didn't find any real improvement by doing that.

  3. Not all browsers give you the same information. That is, parameters, code column, etc.


Caller Function Name

By the way, if you only want the name of the caller function (in most browsers, but not IE) you can use:

arguments.callee.caller.name

But note that this name will be the one after the function keyword. I found no way (even on Google Chrome) to get more than that without getting the code of the whole function.


Caller Function Code

And summarizing the rest of the best answers (by Pablo Cabrera, nourdine, and Greg Hewgill). The only cross-browser and really safe thing you can use is:

arguments.callee.caller.toString();

Which will show the code of the caller function. Sadly, that is not enough for me, and that is why I give you tips for the StackTrace and the caller function Name (although they are not cross-browser).


Try the following code:

function getStackTrace(){
  var f = arguments.callee;
  var ret = [];
  var item = {};
  var iter = 0;

  while ( f = f.caller ){
      // Initialize
    item = {
      name: f.name || null,
      args: [], // Empty array = no arguments passed
      callback: f
    };

      // Function arguments
    if ( f.arguments ){
      for ( iter = 0; iter<f.arguments.length; iter++ ){
        item.args[iter] = f.arguments[iter];
      }
    } else {
      item.args = null; // null = argument listing not supported
    }

    ret.push( item );
  }
  return ret;
}

Worked for me in Firefox-21 and Chromium-25.


I wanted to add my fiddle here for this:

http://jsfiddle.net/bladnman/EhUm3/

I tested this is chrome, safari and IE (10 and 8). Works fine. There is only 1 function that matters, so if you get scared by the big fiddle, read below.

Note: There is a fair amount of my own "boilerplate" in this fiddle. You can remove all of that and use split's if you like. It's just an ultra-safe" set of functions I've come to rely on.

There is also a "JSFiddle" template in there that I use for many fiddles to simply quick fiddling.


It's safer to use *arguments.callee.caller since arguments.caller is deprecated...


As none of previous answers works like what I was looking for(getting just the last function caller not a function as a string or callstack) I post my solution here for those who are like me and hope this will work for them:

_x000D_
_x000D_
function getCallerName(func)_x000D_
{_x000D_
  if (!func) return "anonymous";_x000D_
  let caller = func.caller;_x000D_
  if (!caller) return "anonymous";_x000D_
  caller = caller.toString();_x000D_
  if (!caller.trim().startsWith("function")) return "anonymous";_x000D_
  return caller.substring(0, caller.indexOf("(")).replace("function","");_x000D_
}_x000D_
_x000D_
_x000D_
//  Example of how to use "getCallerName" function_x000D_
_x000D_
function Hello(){_x000D_
console.log("ex1  =>  " + getCallerName(Hello));_x000D_
}_x000D_
_x000D_
function Main(){_x000D_
Hello();_x000D_
_x000D_
// another example_x000D_
console.log("ex3  =>  " + getCallerName(Main));_x000D_
}_x000D_
_x000D_
Main();
_x000D_
_x000D_
_x000D_


Works great for me, and you can chose how much you want to go back in the functions:

function getCaller(functionBack= 0) {
    const back = functionBack * 2;
    const stack = new Error().stack.split('at ');
    const stackIndex = stack[3 + back].includes('C:') ? (3 + back) : (4 + back);
    const isAsync = stack[stackIndex].includes('async');
    let result;
    if (isAsync)
      result = stack[stackIndex].split(' ')[1].split(' ')[0];
    else
      result = stack[stackIndex].split(' ')[0];
    return result;
}

Try accessing this:

arguments.callee.caller.name

Here, everything but the functionname is stripped from caller.toString(), with RegExp.

<!DOCTYPE html>
<meta charset="UTF-8">
<title>Show the callers name</title><!-- This validates as html5! -->
<script>
main();
function main() { Hello(); }
function Hello(){
  var name = Hello.caller.toString().replace(/\s\([^#]+$|^[^\s]+\s/g,'');
  name = name.replace(/\s/g,'');
  if ( typeof window[name] !== 'function' )
    alert ("sorry, the type of "+name+" is "+ typeof window[name]);
  else
    alert ("The name of the "+typeof window[name]+" that called is "+name);
}
</script>

If you just want the function name and not the code, and want a browser-independent solution, use the following:

var callerFunction = arguments.callee.caller.toString().match(/function ([^\(]+)/)[1];

Note that the above will return an error if there is no caller function as there is no [1] element in the array. To work around, use the below:

var callerFunction = (arguments.callee.caller.toString().match(/function ([^\(]+)/) === null) ? 'Document Object Model': arguments.callee.caller.toString().match(/function ([^\(]+)/)[1], arguments.callee.toString().match(/function ([^\(]+)/)[1]);

2018 Update

caller is forbidden in strict mode. Here is an alternative using the (non-standard) Error stack.

The following function seems to do the job in Firefox 52 and Chrome 61-71 though its implementation makes a lot of assumptions about the logging format of the two browsers and should be used with caution, given that it throws an exception and possibly executes two regex matchings before being done.

_x000D_
_x000D_
'use strict';_x000D_
const fnNameMatcher = /([^(]+)@|at ([^(]+) \(/;_x000D_
_x000D_
function fnName(str) {_x000D_
  const regexResult = fnNameMatcher.exec(str);_x000D_
  return regexResult[1] || regexResult[2];_x000D_
}_x000D_
_x000D_
function log(...messages) {_x000D_
  const logLines = (new Error().stack).split('\n');_x000D_
  const callerName = fnName(logLines[1]);_x000D_
_x000D_
  if (callerName !== null) {_x000D_
    if (callerName !== 'log') {_x000D_
      console.log(callerName, 'called log with:', ...messages);_x000D_
    } else {_x000D_
      console.log(fnName(logLines[2]), 'called log with:', ...messages);_x000D_
    }_x000D_
  } else {_x000D_
    console.log(...messages);_x000D_
  }_x000D_
}_x000D_
_x000D_
function foo() {_x000D_
  log('hi', 'there');_x000D_
}_x000D_
_x000D_
(function main() {_x000D_
  foo();_x000D_
}());
_x000D_
_x000D_
_x000D_


function Hello() {
    alert(Hello.caller);
}

Just console log your error stack. You can then know how are you being called

_x000D_
_x000D_
const hello = () => {_x000D_
  console.log(new Error('I was called').stack)_x000D_
}_x000D_
_x000D_
const sello = () => {_x000D_
  hello()_x000D_
}_x000D_
_x000D_
sello()
_x000D_
_x000D_
_x000D_


2018 Update

caller is forbidden in strict mode. Here is an alternative using the (non-standard) Error stack.

The following function seems to do the job in Firefox 52 and Chrome 61-71 though its implementation makes a lot of assumptions about the logging format of the two browsers and should be used with caution, given that it throws an exception and possibly executes two regex matchings before being done.

_x000D_
_x000D_
'use strict';_x000D_
const fnNameMatcher = /([^(]+)@|at ([^(]+) \(/;_x000D_
_x000D_
function fnName(str) {_x000D_
  const regexResult = fnNameMatcher.exec(str);_x000D_
  return regexResult[1] || regexResult[2];_x000D_
}_x000D_
_x000D_
function log(...messages) {_x000D_
  const logLines = (new Error().stack).split('\n');_x000D_
  const callerName = fnName(logLines[1]);_x000D_
_x000D_
  if (callerName !== null) {_x000D_
    if (callerName !== 'log') {_x000D_
      console.log(callerName, 'called log with:', ...messages);_x000D_
    } else {_x000D_
      console.log(fnName(logLines[2]), 'called log with:', ...messages);_x000D_
    }_x000D_
  } else {_x000D_
    console.log(...messages);_x000D_
  }_x000D_
}_x000D_
_x000D_
function foo() {_x000D_
  log('hi', 'there');_x000D_
}_x000D_
_x000D_
(function main() {_x000D_
  foo();_x000D_
}());
_x000D_
_x000D_
_x000D_


function Hello() {
    alert(Hello.caller);
}

You can get the full stacktrace:

arguments.callee.caller
arguments.callee.caller.caller
arguments.callee.caller.caller.caller

Until caller is null.

Note: it cause an infinite loop on recursive functions.


It's safer to use *arguments.callee.caller since arguments.caller is deprecated...


Just console log your error stack. You can then know how are you being called

_x000D_
_x000D_
const hello = () => {_x000D_
  console.log(new Error('I was called').stack)_x000D_
}_x000D_
_x000D_
const sello = () => {_x000D_
  hello()_x000D_
}_x000D_
_x000D_
sello()
_x000D_
_x000D_
_x000D_


Why all of the solutions above look like a rocket science. Meanwhile, it should not be more complicated than this snippet. All credits to this guy

How do you find out the caller function in JavaScript?

var stackTrace = function() {

    var calls = [];
    var caller = arguments.callee.caller;

    for (var k = 0; k < 10; k++) {
        if (caller) {
            calls.push(caller);
            caller = caller.caller;
        }
    }

    return calls;
};

// when I call this inside specific method I see list of references to source method, obviously, I can add toString() to each call to see only function's content
// [function(), function(data), function(res), function(l), function(a, c), x(a, b, c, d), function(c, e)]

I'm attempting to address both the question and the current bounty with this question.

The bounty requires that the caller be obtained in strict mode, and the only way I can see this done is by referring to a function declared outside of strict mode.

For example, the following is non-standard but has been tested with previous (29/03/2016) and current (1st August 2018) versions of Chrome, Edge and Firefox.

_x000D_
_x000D_
function caller()_x000D_
{_x000D_
   return caller.caller.caller;_x000D_
}_x000D_
_x000D_
'use strict';_x000D_
function main()_x000D_
{_x000D_
   // Original question:_x000D_
   Hello();_x000D_
   // Bounty question:_x000D_
   (function() { console.log('Anonymous function called by ' + caller().name); })();_x000D_
}_x000D_
_x000D_
function Hello()_x000D_
{_x000D_
   // How do you find out the caller function is 'main'?_x000D_
   console.log('Hello called by ' + caller().name);_x000D_
}_x000D_
_x000D_
main();
_x000D_
_x000D_
_x000D_


heystewart's answer and JiarongWu's answer both mentioned that the Error object has access to the stack.

Here's an example:

_x000D_
_x000D_
function main() {
  Hello();
}

function Hello() {
  var stack = new Error().stack;
  // N.B. stack === "Error\n  at Hello ...\n  at main ... \n...."
  var m = stack.match(/.*?Hello.*?\n(.*?)\n/);
  if (m) {
    var caller_name = m[1];
    console.log("Caller is:", caller_name)
  }
}

main();
_x000D_
_x000D_
_x000D_

Different browsers shows the stack in different string formats:

Safari  : Caller is: main@https://stacksnippets.net/js:14:8
Firefox : Caller is: main@https://stacksnippets.net/js:14:3
Chrome  : Caller is:     at main (https://stacksnippets.net/js:14:3)
IE Edge : Caller is:    at main (https://stacksnippets.net/js:14:3)
IE      : Caller is:    at main (https://stacksnippets.net/js:14:3)

Most browsers will set the stack with var stack = (new Error()).stack. In Internet Explorer the stack will be undefined - you have to throw a real exception to retrieve the stack.

Conclusion: It's possible to determine "main" is the caller to "Hello" using the stack in the Error object. In fact it will work in cases where the callee / caller approach doesn't work. It will also show you context, i.e. source file and line number. However effort is required to make the solution cross platform.


Works great for me, and you can chose how much you want to go back in the functions:

function getCaller(functionBack= 0) {
    const back = functionBack * 2;
    const stack = new Error().stack.split('at ');
    const stackIndex = stack[3 + back].includes('C:') ? (3 + back) : (4 + back);
    const isAsync = stack[stackIndex].includes('async');
    let result;
    if (isAsync)
      result = stack[stackIndex].split(' ')[1].split(' ')[0];
    else
      result = stack[stackIndex].split(' ')[0];
    return result;
}

I think the following code piece may be helpful:

window.fnPureLog = function(sStatement, anyVariable) {
    if (arguments.length < 1) { 
        throw new Error('Arguments sStatement and anyVariable are expected'); 
    }
    if (typeof sStatement !== 'string') { 
        throw new Error('The type of sStatement is not match, please use string');
    }
    var oCallStackTrack = new Error();
    console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
}

Execute the code:

window.fnPureLog = function(sStatement, anyVariable) {
    if (arguments.length < 1) { 
        throw new Error('Arguments sStatement and anyVariable are expected'); 
    }
    if (typeof sStatement !== 'string') { 
        throw new Error('The type of sStatement is not match, please use string');
    }
    var oCallStackTrack = new Error();
    console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\n' + sStatement + ':', anyVariable);
}

function fnBsnCallStack1() {
    fnPureLog('Stock Count', 100)
}

function fnBsnCallStack2() {
    fnBsnCallStack1()
}

fnBsnCallStack2();

The log looks like this:

Call Stack:
    at window.fnPureLog (<anonymous>:8:27)
    at fnBsnCallStack1 (<anonymous>:13:5)
    at fnBsnCallStack2 (<anonymous>:17:5)
    at <anonymous>:20:1 
Stock Count: 100

As none of previous answers works like what I was looking for(getting just the last function caller not a function as a string or callstack) I post my solution here for those who are like me and hope this will work for them:

_x000D_
_x000D_
function getCallerName(func)_x000D_
{_x000D_
  if (!func) return "anonymous";_x000D_
  let caller = func.caller;_x000D_
  if (!caller) return "anonymous";_x000D_
  caller = caller.toString();_x000D_
  if (!caller.trim().startsWith("function")) return "anonymous";_x000D_
  return caller.substring(0, caller.indexOf("(")).replace("function","");_x000D_
}_x000D_
_x000D_
_x000D_
//  Example of how to use "getCallerName" function_x000D_
_x000D_
function Hello(){_x000D_
console.log("ex1  =>  " + getCallerName(Hello));_x000D_
}_x000D_
_x000D_
function Main(){_x000D_
Hello();_x000D_
_x000D_
// another example_x000D_
console.log("ex3  =>  " + getCallerName(Main));_x000D_
}_x000D_
_x000D_
Main();
_x000D_
_x000D_
_x000D_


I'm attempting to address both the question and the current bounty with this question.

The bounty requires that the caller be obtained in strict mode, and the only way I can see this done is by referring to a function declared outside of strict mode.

For example, the following is non-standard but has been tested with previous (29/03/2016) and current (1st August 2018) versions of Chrome, Edge and Firefox.

_x000D_
_x000D_
function caller()_x000D_
{_x000D_
   return caller.caller.caller;_x000D_
}_x000D_
_x000D_
'use strict';_x000D_
function main()_x000D_
{_x000D_
   // Original question:_x000D_
   Hello();_x000D_
   // Bounty question:_x000D_
   (function() { console.log('Anonymous function called by ' + caller().name); })();_x000D_
}_x000D_
_x000D_
function Hello()_x000D_
{_x000D_
   // How do you find out the caller function is 'main'?_x000D_
   console.log('Hello called by ' + caller().name);_x000D_
}_x000D_
_x000D_
main();
_x000D_
_x000D_
_x000D_


Try the following code:

function getStackTrace(){
  var f = arguments.callee;
  var ret = [];
  var item = {};
  var iter = 0;

  while ( f = f.caller ){
      // Initialize
    item = {
      name: f.name || null,
      args: [], // Empty array = no arguments passed
      callback: f
    };

      // Function arguments
    if ( f.arguments ){
      for ( iter = 0; iter<f.arguments.length; iter++ ){
        item.args[iter] = f.arguments[iter];
      }
    } else {
      item.args = null; // null = argument listing not supported
    }

    ret.push( item );
  }
  return ret;
}

Worked for me in Firefox-21 and Chromium-25.


Try accessing this:

arguments.callee.caller.name

I would do this:

function Hello() {
  console.trace();
}

here is a function to get full stacktrace:

function stacktrace() {
var f = stacktrace;
var stack = 'Stack trace:';
while (f) {
  stack += '\n' + f.name;
  f = f.caller;
}
return stack;
}

You can use Function.Caller to get the calling function. The old method using argument.caller is considered obsolete.

The following code illustrates its use:

function Hello() { return Hello.caller;}

Hello2 = function NamedFunc() { return NamedFunc.caller; };

function main()
{
   Hello();  //both return main()
   Hello2();
}

Notes about obsolete argument.caller: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller

Be aware Function.caller is non-standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller


As far as I know, we have 2 way for this from given sources like this-

  1. arguments.caller

    function whoCalled()
    {
        if (arguments.caller == null)
           console.log('I was called from the global scope.');
        else
           console.log(arguments.caller + ' called me!');
    }
    
  2. Function.caller

    function myFunc()
    {
       if (myFunc.caller == null) {
          return 'The function was called from the top!';
       }
       else
       {
          return 'This function\'s caller was ' + myFunc.caller;
        }
    }
    

Think u have your answer :).


Try accessing this:

arguments.callee.caller.name

It's safer to use *arguments.callee.caller since arguments.caller is deprecated...


heystewart's answer and JiarongWu's answer both mentioned that the Error object has access to the stack.

Here's an example:

_x000D_
_x000D_
function main() {
  Hello();
}

function Hello() {
  var stack = new Error().stack;
  // N.B. stack === "Error\n  at Hello ...\n  at main ... \n...."
  var m = stack.match(/.*?Hello.*?\n(.*?)\n/);
  if (m) {
    var caller_name = m[1];
    console.log("Caller is:", caller_name)
  }
}

main();
_x000D_
_x000D_
_x000D_

Different browsers shows the stack in different string formats:

Safari  : Caller is: main@https://stacksnippets.net/js:14:8
Firefox : Caller is: main@https://stacksnippets.net/js:14:3
Chrome  : Caller is:     at main (https://stacksnippets.net/js:14:3)
IE Edge : Caller is:    at main (https://stacksnippets.net/js:14:3)
IE      : Caller is:    at main (https://stacksnippets.net/js:14:3)

Most browsers will set the stack with var stack = (new Error()).stack. In Internet Explorer the stack will be undefined - you have to throw a real exception to retrieve the stack.

Conclusion: It's possible to determine "main" is the caller to "Hello" using the stack in the Error object. In fact it will work in cases where the callee / caller approach doesn't work. It will also show you context, i.e. source file and line number. However effort is required to make the solution cross platform.


Another way around this problem is to simply pass the name of the calling function as a parameter.

For example:

function reformatString(string, callerName) {

    if (callerName === "uid") {
        string = string.toUpperCase();
    }

    return string;
}

Now, you could call the function like this:

function uid(){
    var myString = "apples";

    reformatString(myString, function.name);
}

My example uses a hard coded check of the function name, but you could easily use a switch statement or some other logic to do what you want there.


To recap (and make it clearer) ...

this code:

function Hello() {
    alert("caller is " + arguments.callee.caller.toString());
}

is equivalent to this:

function Hello() {
    alert("caller is " + Hello.caller.toString());
}

Clearly the first bit is more portable, since you can change the name of the function, say from "Hello" to "Ciao", and still get the whole thing to work.

In the latter, in case you decide to refactor the name of the invoked function (Hello), you would have to change all its occurrences :(


I usually use (new Error()).stack in Chrome. The nice thing is that this also gives you the line numbers where the caller called the function. The downside is that it limits the length of the stack to 10, which is why I came to this page in the first place.

(I'm using this to collect callstacks in a low-level constructor during execution, to view and debug later, so setting a breakpoint isn't of use since it will be hit thousands of times)


I know you mentioned "in Javascript", but if the purpose is debugging, I think it's easier to just use your browser's developer tools. This is how it looks in Chrome: enter image description here Just drop the debugger where you want to investigate the stack.


Note you can't use Function.caller in Node.js, use caller-id package instead. For example:

var callerId = require('caller-id');

function foo() {
    bar();
}
function bar() {
    var caller = callerId.getData();
    /*
    caller = {
        typeName: 'Object',
        functionName: 'foo',
        filePath: '/path/of/this/file.js',
        lineNumber: 5,
        topLevelFlag: true,
        nativeFlag: false,
        evalFlag: false
    }
    */
}

If you are not going to run it in IE < 11 then console.trace() would suit.

function main() {
    Hello();
}

function Hello() {
    console.trace()
}

main()
// Hello @ VM261:9
// main @ VM261:4

I wanted to add my fiddle here for this:

http://jsfiddle.net/bladnman/EhUm3/

I tested this is chrome, safari and IE (10 and 8). Works fine. There is only 1 function that matters, so if you get scared by the big fiddle, read below.

Note: There is a fair amount of my own "boilerplate" in this fiddle. You can remove all of that and use split's if you like. It's just an ultra-safe" set of functions I've come to rely on.

There is also a "JSFiddle" template in there that I use for many fiddles to simply quick fiddling.


If you just want the function name and not the code, and want a browser-independent solution, use the following:

var callerFunction = arguments.callee.caller.toString().match(/function ([^\(]+)/)[1];

Note that the above will return an error if there is no caller function as there is no [1] element in the array. To work around, use the below:

var callerFunction = (arguments.callee.caller.toString().match(/function ([^\(]+)/) === null) ? 'Document Object Model': arguments.callee.caller.toString().match(/function ([^\(]+)/)[1], arguments.callee.toString().match(/function ([^\(]+)/)[1]);

Why all of the solutions above look like a rocket science. Meanwhile, it should not be more complicated than this snippet. All credits to this guy

How do you find out the caller function in JavaScript?

var stackTrace = function() {

    var calls = [];
    var caller = arguments.callee.caller;

    for (var k = 0; k < 10; k++) {
        if (caller) {
            calls.push(caller);
            caller = caller.caller;
        }
    }

    return calls;
};

// when I call this inside specific method I see list of references to source method, obviously, I can add toString() to each call to see only function's content
// [function(), function(data), function(res), function(l), function(a, c), x(a, b, c, d), function(c, e)]

I know you mentioned "in Javascript", but if the purpose is debugging, I think it's easier to just use your browser's developer tools. This is how it looks in Chrome: enter image description here Just drop the debugger where you want to investigate the stack.


Another way around this problem is to simply pass the name of the calling function as a parameter.

For example:

function reformatString(string, callerName) {

    if (callerName === "uid") {
        string = string.toUpperCase();
    }

    return string;
}

Now, you could call the function like this:

function uid(){
    var myString = "apples";

    reformatString(myString, function.name);
}

My example uses a hard coded check of the function name, but you could easily use a switch statement or some other logic to do what you want there.


As far as I know, we have 2 way for this from given sources like this-

  1. arguments.caller

    function whoCalled()
    {
        if (arguments.caller == null)
           console.log('I was called from the global scope.');
        else
           console.log(arguments.caller + ' called me!');
    }
    
  2. Function.caller

    function myFunc()
    {
       if (myFunc.caller == null) {
          return 'The function was called from the top!';
       }
       else
       {
          return 'This function\'s caller was ' + myFunc.caller;
        }
    }
    

Think u have your answer :).


I would do this:

function Hello() {
  console.trace();
}

StackTrace

You can find the entire stack trace using browser specific code. The good thing is someone already made it; here is the project code on GitHub.

But not all the news is good:

  1. It is really slow to get the stack trace so be careful (read this for more).

  2. You will need to define function names for the stack trace to be legible. Because if you have code like this:

    var Klass = function kls() {
       this.Hello = function() { alert(printStackTrace().join('\n\n')); };
    }
    new Klass().Hello();
    

    Google Chrome will alert ... kls.Hello ( ... but most browsers will expect a function name just after the keyword function and will treat it as an anonymous function. An not even Chrome will be able to use the Klass name if you don't give the name kls to the function.

    And by the way, you can pass to the function printStackTrace the option {guess: true} but I didn't find any real improvement by doing that.

  3. Not all browsers give you the same information. That is, parameters, code column, etc.


Caller Function Name

By the way, if you only want the name of the caller function (in most browsers, but not IE) you can use:

arguments.callee.caller.name

But note that this name will be the one after the function keyword. I found no way (even on Google Chrome) to get more than that without getting the code of the whole function.


Caller Function Code

And summarizing the rest of the best answers (by Pablo Cabrera, nourdine, and Greg Hewgill). The only cross-browser and really safe thing you can use is:

arguments.callee.caller.toString();

Which will show the code of the caller function. Sadly, that is not enough for me, and that is why I give you tips for the StackTrace and the caller function Name (although they are not cross-browser).


Looks like this is quite a solved question but I recently found out that callee is not allowed in 'strict mode' so for my own use I wrote a class that will get the path from where it is called. It's part of a small helper lib and if you want to use the code standalone change the offset used to return the stack trace of the caller (use 1 instead of 2)

function ScriptPath() {
  var scriptPath = '';
  try {
    //Throw an error to generate a stack trace
    throw new Error();
  }
  catch(e) {
    //Split the stack trace into each line
    var stackLines = e.stack.split('\n');
    var callerIndex = 0;
    //Now walk though each line until we find a path reference
    for(var i in stackLines){
      if(!stackLines[i].match(/http[s]?:\/\//)) continue;
      //We skipped all the lines with out an http so we now have a script reference
      //This one is the class constructor, the next is the getScriptPath() call
      //The one after that is the user code requesting the path info (so offset by 2)
      callerIndex = Number(i) + 2;
      break;
    }
    //Now parse the string for each section we want to return
    pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
  }

  this.fullPath = function() {
    return pathParts[1];
  };

  this.path = function() {
    return pathParts[2];
  };

  this.file = function() {
    return pathParts[3];
  };

  this.fileNoExt = function() {
    var parts = this.file().split('.');
    parts.length = parts.length != 1 ? parts.length - 1 : 1;
    return parts.join('.');
  };
}

In both ES6 and Strict mode, use the following to get the Caller function

console.log((new Error()).stack.split("\n")[2].trim().split(" ")[1])

Please note that, the above line will throw an exception, if there is no caller or no previous stack. Use accordingly.

To get callee (the current function name), use:

console.log((new Error()).stack.split("\n")[1].trim().split(" ")[1]) 

You can use Function.Caller to get the calling function. The old method using argument.caller is considered obsolete.

The following code illustrates its use:

function Hello() { return Hello.caller;}

Hello2 = function NamedFunc() { return NamedFunc.caller; };

function main()
{
   Hello();  //both return main()
   Hello2();
}

Notes about obsolete argument.caller: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller

Be aware Function.caller is non-standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller