How to Find out the Caller Function in JavaScript

To find out the caller function, name a non-standard the function.caller property in JavaScript. The Function object is replaced by the name of the function of which you need to find out the parent function name.

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

If the function Welcome was invoked by the top-level code, the value of Welcome.caller is null, otherwise, it is the function that called Welcome.

The function.caller is a non-standard feature and is not on a standards, thus avoid using it on production sites that face the Web as it won’t work for every user. However, function.caller is the accepted method to get the call stack.

There is another method which is no longer supported in modern JavaScript:

function Welcome() {
  alert("caller is " + arguments.callee.caller.toString());
}
Welcome();
function Welcome() {
   if (arguments.caller == null){   //Does not match
      console.log('I was called from the global scope.');
   }else{
      console.log(arguments.caller + ' called me!');  // Does not match
   }
  alert(Welcome.caller);  // Does not match
  alert(Welcome.arguments);  // Does not match
}
Welcome();

The function.caller property replaces the above obsolete arguments.caller property of the arguments object. The arguments.caller property is obsolete, which used to provide the function that called the currently executing function.

Though it may still work in some major browsers, its use is not recommended, as it could be removed at any time.

The function.caller Property

The function.caller property returns the function that called the specified function. It will return null for strict, generator function callers and async function.

Do you find this helpful?

Related articles