UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ Function/ ""Function:

The optional displayName property of a Function instance specifies the display name of the function.

Value

The displayName property is not initially present on any function — it's added by the code authors. For the purpose of display, it should be a string.

Description

The displayName property, if present, may be preferred by consoles and profilers over the name property to be displayed as the name of a function.

Among browsers, only the Firefox console utilizes this property. React devtools also use the displayName property when displaying the component tree.

Firefox does some basic attempts to decode the displayName that's possibly generated by the anonymous JavaScript functions naming convention algorithm. The following patterns are detected:

If none of the above patterns match, the entire displayName is displayed.

Examples

Setting a displayName

By entering the following in a Firefox console, it should display as something like function MyFunction():

const a = function () {};
a.displayName = "MyFunction";

a; // function MyFunction()

Changing displayName dynamically

You can dynamically change the displayName of a function:

const object = {
  // anonymous
  someMethod: function someMethod(value) {
    someMethod.displayName = `someMethod (${value})`;
  },
};

console.log(object.someMethod.displayName); // undefined

object.someMethod("123");
console.log(object.someMethod.displayName); // "someMethod (123)"

Cleaning of displayName

Firefox devtools would clean up a few common patterns in the displayName property before displaying it.

function foo() {}

function testName(name) {
  foo.displayName = name;
  console.log(foo);
}

testName("$foo$"); // function $foo$()
testName("foo bar"); // function bar()
testName("Foo.prototype.add"); // function add()
testName("foo ."); // function foo .()
testName("foo <"); // function foo <()
testName("foo?"); // function foo?()
testName("foo()"); // function foo()()

testName("[...]"); // function ...()
testName("foo<"); // function foo()
testName("foo..."); // function foo()
testName("foo(^)"); // function foo()

Specifications

Not part of any standard.

Browser compatibility

See also