- Function: name
- Try it
- Value
- Description
- Function declaration
- Default-exported function declaration
- Function constructor
- Function expression
- Variable declaration and method
- Initializer and default value
- Shorthand method
- Bound function
- Getter and setter
- Class
- Symbol as function name
- Private property
- Examples
- Telling the constructor name of an object
- JavaScript compressors and minifiers
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- How to Call a Dynamically-Named Method in JavaScript
- How do I call a dynamically-named method in Javascript?
- How to call a function using a dynamic name in JS
- Dynamic function name in javascript?
- How do I call a dynamically-named method with for in Javascript
- Javascript Dynamic Function Call with Name
- Dynamic function names in JavaScript
Function: name
The name data property of a Function instance indicates the function’s name as specified when it was created, or it may be either anonymous or » (an empty string) for functions created anonymously.
Try it
Value
Property attributes of Function: name | |
---|---|
Writable | no |
Enumerable | no |
Configurable | yes |
Note: In non-standard, pre-ES2015 implementations the configurable attribute was false as well.
Description
The function’s name property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself.
The name property is read-only and cannot be changed by the assignment operator:
function someFunction() > someFunction.name = "otherFunction"; console.log(someFunction.name); // someFunction
The name property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred.
Function declaration
The name property returns the name of a function declaration.
function doSomething() > doSomething.name; // "doSomething"
Default-exported function declaration
An export default declaration exports the function as a declaration instead of an expression. If the declaration is anonymous, the name is «default» .
// -- someModule.js -- export default function () > // -- main.js -- import someModule from "./someModule.js"; someModule.name; // "default"
Function constructor
Functions created with the Function() constructor have name «anonymous».
new Function().name; // "anonymous"
Function expression
If the function expression is named, that name is used as the name property.
const someFunction = function someFunctionName() >; someFunction.name; // "someFunctionName"
Anonymous function expressions created using the keyword function or arrow functions would have «» (an empty string) as their name.
However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it’s created (such as in a variable declaration). In such cases, the name can be inferred, as the following few subsections demonstrate.
One practical case where the name cannot be inferred is a function returned from another function:
function getFoo() return () => >; > getFoo().name; // ""
Variable declaration and method
Variables and methods can infer the name of an anonymous function from its syntactic position.
const f = function () >; const object = someMethod: function () >, >; console.log(f.name); // "f" console.log(object.someMethod.name); // "someMethod"
The same applies to assignment:
Initializer and default value
Functions in initializers (default values) of destructuring, default parameters, class fields, etc., will inherit the name of the bound identifier as their name .
const [f = () => >] = []; f.name; // "f" const someMethod: m = () => > > = >; m.name; // "m" function foo(f = () => >) console.log(f.name); > foo(); // "f" class Foo static someMethod = () => >; > Foo.someMethod.name; // someMethod
Shorthand method
const o = foo() >, >; o.foo.name; // "foo";
Bound function
Function.prototype.bind() produces a function whose name is «bound » plus the function name.
function foo() > foo.bind(>).name; // "bound foo"
Getter and setter
When using get and set accessor properties, «get» or «set» will appear in the function name.
const o = get foo() >, set foo(x) >, >; const descriptor = Object.getOwnPropertyDescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo";
Class
A class’s name follows the same algorithm as function declarations and expressions.
Warning: JavaScript will set the function’s name property only if a function does not have an own property called name . However, classes’ static members will be set as own properties of the class constructor function, and thus prevent the built-in name from being applied. See an example below.
Symbol as function name
If a Symbol is used a function name and the symbol has a description, the method’s name is the description in square brackets.
const sym1 = Symbol("foo"); const sym2 = Symbol(); const o = [sym1]() >, [sym2]() >, >; o[sym1].name; // "[foo]" o[sym2].name; // "[]"
Private property
Private fields and private methods have the hash ( # ) as part of their names.
class Foo #field = () => >; #method() > getNames() console.log(this.#field.name); console.log(this.#method.name); > > new Foo().getNames(); // "#field" // "#method"
Examples
Telling the constructor name of an object
You can use obj.constructor.name to check the «class» of an object.
function Foo() > // Or: class Foo <> const fooInstance = new Foo(); console.log(fooInstance.constructor.name); // "Foo"
However, because static members will become own properties of the class, we can’t obtain the class name for virtually any class with a static method property name() :
class Foo constructor() > static name() > >
With a static name() method Foo.name no longer holds the actual class name but a reference to the name() function object. Trying to obtain the class of fooInstance via fooInstance.constructor.name won’t give us the class name at all, but instead a reference to the static class method. Example:
const fooInstance = new Foo(); console.log(fooInstance.constructor.name); // ƒ name() <>
Due to the existence of static fields, name may not be a function either.
class Foo static name = 123; > console.log(new Foo().constructor.name); // 123
If a class has a static property called name , it will also become writable. The built-in definition in the absence of a custom static definition is read-only:
.name = "Hello"; console.log(Foo.name); // "Hello" if class Foo has a static "name" property, but "Foo" if not.
Therefore you may not rely on the built-in name property to always hold a class’s name.
JavaScript compressors and minifiers
Warning: Be careful when using the name property with source-code transformations, such as those carried out by JavaScript compressors (minifiers) or obfuscators. These tools are often used as part of a JavaScript build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function’s name at build time.
function Foo() > const foo = new Foo(); if (foo.constructor.name === "Foo") console.log("'foo' is an instance of 'Foo'"); > else console.log("Oops!"); >
function a() > const b = new a(); if (b.constructor.name === "Foo") console.log("'foo' is an instance of 'Foo'"); > else console.log("Oops!"); >
In the uncompressed version, the program runs into the truthy branch and logs «‘foo’ is an instance of ‘Foo'» — whereas, in the compressed version it behaves differently, and runs into the else branch. If you rely on the name property, like in the example above, make sure your build pipeline doesn’t change function names, or don’t assume a function has a particular name.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 12, 2023 by MDN contributors.
Your blueprint for a better internet.
How to Call a Dynamically-Named Method in JavaScript
How do I call a dynamically-named method in Javascript?
Assuming the populate_Colours method is in the global namespace, you may use the following code, which exploits both that all object properties may be accessed as though the object were an associative array, and that all global objects are actually properties of the window host object.
var method_name = "Colours";
var method_prefix = "populate_";
// Call function:
window[method_prefix + method_name](arg1, arg2);
How to call a function using a dynamic name in JS
Usually we should avoid eval. What you are trying to do is possible without using eval too and with a simpler code :
//variables
var ta = 3213;
var da = 44;
var s = [];
//Create string representation of function
s[1] = function test0()< alert(" + da + "); >;
s[0] = function test1()< alert(" + ta +"); >;
s.forEach((fun) => < this[fun.name] = fun;>);
// calling the function
this["test"+1]();
Or simple in your code do :
If you are using string and eval just because you are getting function name as string, instead you can create an object :
var data = <>;
for(var i = 0; i data['key'+ i] = function (i) < alert(i); >.bind(null, i);
>
Dynamic function name in javascript?
As others mentioned, this is not the fastest nor most recommended solution. Marcosc’s solution below is the way to go.
var code = "this.f = function " + instance + "() ";
eval(code);
How do I call a dynamically-named method with for in Javascript
If the functions are globally accessible you may write
Otherwise, you may be able to rewrite your code to add all the functions to one variable:
var f = a1: function() < >,
a2: function() < >,
a3: function() < >
>;
If you’re rewriting, since all functions are named by an index, you might as well write:
var myFunctions = [
function() < >,
function() < >,
function() < >
];
. and call myFunctions[i]() . (Of course, as Felix Kling points out in comments, i here would have to be adjusted to be 0-based).
Javascript Dynamic Function Call with Name
Since you want to call functions using bracket notation in object scope, not window scope, you can use this instead of window :
function meth_4()
this["meth_1"]();
this["meth_2"]();
this["meth_3"]();
>
Dynamic function names in JavaScript
Updated answer in 2016:
The «However, that’s changing. » part of the original answer below has changed. ES2015 («ES6») was released a year ago, and JavaScript engines are now finally coming into compliance with one of its lesser-known aspects: Function#name .
As of ES2015, this function has a name despite being created using an «anonymous» function expression:
Its name is f . This is dictated by the specification (or the new one for ES2016) in dozens of different places (search for where SetFunctionName is used). In this particular case, it’s because it gets the name of the variable it’s being assigned to. (I’ve used var there instead of the new let to avoid giving the impression that this is a feature of let . It isn’t. But as this is ES2015, I’ll use let from now on. )
Now, you may be thinking «That doesn’t help me, because the f is hardcoded,» but stick with me.
This function also has the name f :
It gets the name of the property it’s being assigned to ( f ). And that’s where another handy feature of ES2015 comes into effect: Computed property names in object initializers. Instead of giving the name f literally, we can use a computed property name:
let functionName = "f";
let obj = [functionName]: function() < >
>;
Computed property name syntax evaluates the expression in the [] and then uses the result as the property name. And since the function gets a true name from the property it’s being assigned to, voilà, we can create a function with a runtime-determined name.
If we don’t want the object for anything, we don’t need to keep it:
let functionName = "f";
let f = ( [functionName]: function() < >
>)[functionName];
That creates the object with the function on it, then grabs the function from the object and throws the object away.
Of course, if you want to use lexical this , it could be an arrow function instead:
let functionName = "f";
let f = ( [functionName]: () => < >
>)[functionName];
Here’s an example, which works on Chrome 51 and later but not on many others yet:
// Get the namelet functionName = prompt( "What name for the function?", "func" + Math.floor(Math.random() * 10000));
// Create the functionlet f = (< [functionName]: function() < >>)[functionName];
// Check the nameif (f.name !== functionName) < console.log("This browser's JavaScript engine doesn't fully support ES2015 yet.");>else