Home

JavaScript: How to get the caller (parent) function's name

I recently had the need to find out the name of the function that was invoking another specific function in a NodeJS code base.

Doing this is usually a hacky solution to a deeper underlying problem. In my case, it had to do with mocking and spying during tests.

While it probably should NOT be used in production code, I found it fun and will share bellow two ways it can be achieved.

The Short Way

Despite all the fuzz about Function.caller being deprecated, using arguments.callee.caller.name gave me no errors in NodeJS’ strict mode.

Here is some reference on what is and what is not deprecated.

./index.js
function parent() {
  child();
}

function child() {
  const caller = arguments.callee.caller.name;
  console.log(caller);
}

parent(); // console logs 'parent'

The Creative Way

Don’t want to care about what is deprecated and what is not?

The creative way bellow throws an error and gets the function name from the stack trace.

./index.js
function whoIsMyDaddy() {
  try {
    throw new Error();
  } catch (e) {
    // matches this function, the caller and the parent
    const allMatches = e.stack.match(/(\w+)@|at (\w+) \(/g);
    // match parent function name
    const parentMatches = allMatches[2].match(/(\w+)@|at (\w+) \(/);
    // return only name
    return parentMatches[1] || parentMatches[2];
  }
}

function child() {
  let caller = whoIsMyDaddy();
  console.log(caller);
}

function parent() {
  child();
}

parent(); // console logs 'parent'