Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7568279
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T14:53:05+00:00 2026-05-30T14:53:05+00:00

Is there any way to create a function with a real name that’s determined

  • 0

Is there any way to create a function with a real name that’s determined at runtime without using eval, and using only pure JavaScript? (So, no generated script elements, as those are specific to the browser environment [and in many ways would be eval in disguise anyway]; no using non-standard features of one particular JavaScript engine, etc.)

Note that I’m specifically not asking about anonymous functions referenced by variables or properties that have names, e.g.:

// NOT this
var name = /* ...come up with the name... */;
var obj = {};
obj[name] = function() { /* ... */ };

There, while the object property has a name, the function does not. Anonymous functions are fine for lots of things, but not what I’m looking for here. I want the function to have a name (e.g., to show up in call stacks in debuggers, etc.).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T14:53:07+00:00Added an answer on May 30, 2026 at 2:53 pm

    The Answer for ECMAScript 2015+ (aka "ES6"):

    Yes. As of ES2015, the function created by an anonymous function expression assigned to an object property takes the name of that object property. This is implemented in all modern browsers, although Edge and Safari don’t use the name in stack traces. We can use that in combination with another ES2015 feature (computed property names) to name a function without new Function or eval.

    In ES2015 this creates a function named "foo###" where ### is 1-3 digits:

    const dynamicName = "foo" + Math.floor(Math.random() * 1000);
    const obj = {
        [dynamicName]() {
            throw new Error();
        },
    };
    const f = obj[dynamicName];
    // See its `name` property
    console.log(
        "Function's `name` property: " + f.name + " (see compatibility note)"
    );
    // We can see whether it has a name in stack traces via an exception
    try {
        f();
    } catch (e) {
        console.log(e.stack);
    }

    It would also work with [dynamicName]: function() { }, method syntax isn’t required, function syntax is fine. Which is handy if you want to create a constructor function this way:

    const dynamicName = "Foo" + Math.floor(Math.random() * 1000);
    const obj = {
        [dynamicName]: function (throwError = false) {
            if (throwError) {
                throw new Error();
            }
        },
    };
    const F = obj[dynamicName];
    // See its `name` property
    console.log(
        "Function's `name` property: " + F.name + " (see compatibility note)"
    );
    // We can see whether it has a name in stack traces via an exception
    try {
        new F(true);
    } catch (e) {
        console.log(e.stack);
    }
    // And we can see it works as a constructor:
    const inst = new F();
    console.log(inst instanceof F); // true

    Of course, this is ES2015+, so you could also use class to create a constructor, [dynamicName]: class { }:

    const dynamicName = "Foo" + Math.floor(Math.random() * 1000);
    const obj = {
        [dynamicName]: class {
            constructor(throwError = false) {
                if (throwError) {
                    throw new Error();
                }
            }
        },
    };
    const F = obj[dynamicName];
    // See its `name` property
    console.log(
        "Function's `name` property: " + F.name + " (see compatibility note)"
    );
    // We can see whether it has a name in stack traces via an exception
    try {
        new F(true);
    } catch (e) {
        console.log(e.stack);
    }
    // And we can see it works as a constructor:
    const inst = new F();
    console.log(inst instanceof F); // true

    The Answer for ECMAScript 5 (from 2012):

    No. You cannot do that without eval or its cousin the Function constructor. Your choices are:

    1. Live with an anonymous function instead. Modern engines do things to help debugging with those.

    2. Use eval.

    3. Use the Function constructor.

    Details:

    1. Live with an anonymous function instead. Many modern engines will show a useful name (e.g., in call stacks and such) if you have a nice, unambiguous var name = function() { ... }; expression (showing the name of the variable), even though technically the function doesn’t have a name. (In ES2015+, functions created that way will actually have names.) Either way, though, if you want a truly runtime-defined name (a name coming from a variable), you’re pretty much stuck.

    2. Use eval. eval is evil when you can avoid it, but with strings you’re in total control of, in a scope you control, with an understanding of the costs (you’re firing up a JavaScript parser), to do something you cannot do otherwise (as in this case), it’s fine provided you really need to do that thing. But if you’re not in control of the string or scope, or you don’t want the cost, you’ll have to live with an anonymous function.

      Here’s how the eval option looks:

       // Remember, this is old-style ES5 code
       var name = "foo" + Math.floor(Math.random() * 1000);
       var f = eval(
           "(function() {\n" +
           "    function " + name + "() {\n" +
           "        console.log('Hi');\n" +
           "    }\n" +
           "    return " + name + ";\n" +
           "})();"
       );
       console.log(f.name);
       f();
      

      That creates a function with the name we come up with at runtime without leaking the name into the containing scope, assigning a reference to that function to f. (And it formats the code nicely so single-stepping through it in a debugger is easy.)

      This didn’t used to correctly assign the name (surprisingly) in older versions of Firefox. As of the current version of their JavaScript engine in Firefox 29, it does.

      Because that uses eval, the function you create has access to the scope in which it was created, which is important if you’re a tidy coder who avoids global symbols. So this works, for instance:

       // Remember, this is old-style ES5 code
       (function() {
           function display(msg) {
               console.log(msg);
           }
      
           var name = "foo" + Math.floor(Math.random() * 1000);
           var f = eval(
               "(function() {\n" +
               "   function " + name + "() {\n" +
               "       display('Hi');\n" +         // <=== Uses the
               "   }\n" +                          //      function above
               "   return " + name + ";\n" +
               "})();"
           );
           console.log(f.name);
           f();
       })();
       console.log(typeof display); // undefined (because it's not a global)
      
    3. Use the Function constructor, as demonstrated in this article by Marcos Cáceres:

       // Remember, this is old-style ES5 code
       var name = "foo" + Math.floor(Math.random() * 1000);
       var f = new Function(
           "return function " + name + "() {\n" +
           "    console.log('Hi!');\n" +
           "};"
       )();
       console.log(f.name);
       f();
      

      There we create a temporary anonymous function (the one created via the Function constructor) and call it; that temporary anonymous function creates a named function using a named function expression.

      This is shorter than the eval version, and functions created via the Function constructor do not have access to the scope in which they were created. So the example above using display would fail, because display wouldn’t be in-scope for the created function. So not an option for tidy coders avoiding global symbols, but useful for those times when you want to disassociate the generated function from the scope in which you’re generating it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there any way to create a function/callable object that inherits properties from another
Is there any way to create C# 3.0 anonymous object via Reflection at runtime
Is there any way to create a pivot and/or cross-tab query using for SQLite
I am just wondering if there is any way to create the same function
Is there any way to create an implode routine in PL/SQL that takes any
Is there any way to create a virtual drive in (My) Computer and manipulate
Is there any way to create the query parameters for doing a GET request
Is there any way to create a new NSString from a format string like
Is there any way to create a naming convention for my primary key constraints
Is there any way to create a property like this C# property in Objective-C?

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.