Function.name

This is an experimental technology, part of the Harmony (ECMAScript 6) proposal.
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

Summary

The function.name property returns the name of the function.

Description

The name property returns the name of a function, or an empty string for anonymous functions:

function doSomething() { }

alert(doSomething.name); // alerts "doSomething"

Functions created with the syntax new Function(...) or just Function(...) have their name property set to an empty string. In the following examples anonymous functions are created, so name returns an empty string:

var f = function() { };
var object = {
  someMethod: function() {}
};

alert(f.name == ""); // true
alert(object.someMethod.name == ""); // also true

You can define a function with a name in a function expression:

var object = {
  someMethod: function object_someMethod() {}
};
alert(object.someMethod.name); // alerts "object_someMethod"

try { object_someMethod } catch(e) { alert(e); }
// ReferenceError: object_someMethod is not defined

You cannot change the name of a function, this property is read-only:

var object = {
  // anonymous
  someMethod: function() { }
};

object.someMethod.name = "someMethod";
alert(object.someMethod.name); // empty string, someMethod is anonymous

Examples

You can use obj.constructor.name to check the "class" of an object:

function a() { }

var b = new a();

alert(b.constructor.name); //Alerts "a"

Specifications

Specification Status Comment
ECMAScript Language Specification 6th Edition (ECMA-262) Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) Not supported (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) Not supported (Yes) (Yes)

 

Document Tags and Contributors

Last updated by: fscholz,