DEV Community

loading...

A Me() function for JavaScript and Google Apps Script

Bruce Axtens
Programmed Canon Canola calculators in 1977. Assorted platforms and languages ever since. Assisting with HOPL.info. I am NOT looking for work -- I've got more than enough to do.
・1 min read

Quite a while back I wrote about a Me function for C#. I used to have an equivalent in JavaScript ES3. It used the now-deprecated arguments vector, which had to be passed in on the call:

function Me(a) {
    return a.callee.toString().split(" ")[1].split("(")[0].trim();
}

// example usage. 
function foo() {
  Logger.log("[%s] We are in function %s", Me(arguments), Me(arguments));
}
Enter fullscreen mode Exit fullscreen mode

I recently discovered a way that works for more recent JavaScripts including Google Apps Script. I expect it is not the most performant and should not be used in a Production environment. It's proving very helpful in Development.

The code below is TypeScript. Remove the : string and the exclamation mark after stack and you should have working JavaScript.

function Me() : string {
    const e = new Error();
    const frame = e.stack!.split("\n")[2];
    const functionName = frame.split(" ")[5];
    return functionName;
}
Enter fullscreen mode Exit fullscreen mode

The function can be used for logging and who knows what else:

function foo() {
  Logger.log("[%s] We are in function %s", Me(), Me());
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)