DEV Community

Bruce Axtens
Bruce Axtens

Posted on

1 2

A Me() function for JavaScript and Google Apps Script

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

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay