Search code examples
javascriptcallstack

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?


Solution

  • Note that this solution is deprecated and should no longer be used according to MDN documentation

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller


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

    Note that this feature is non-standard, from Function.caller:

    Non-standard
    This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


    The following is the old answer from 2008, which is no longer supported in modern Javascript:

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