In JavaScript, functions are objects and come with built-in properties. The name property is used to identify a function by returning the name assigned at the time of its creation.
- Function.name returns the original name of the function.
- The name property is read-only and cannot be modified.
- It is useful for debugging, logging, and stack traces.
function greet() {
console.log("Hello!");
}
console.log(greet.name);
Syntax:
Function.nameProperty Values: This property has three attributes as mentioned below:
- Writable: No
- readable: No
- configurable: Yes
Return Value: This property returns the string i.e the name of the function.
Example: Below is a Basic example of the Function name Property.
// Creating function name func1
function func1() {
}
console.log(func1.name)
More examples for the above property are provided below:
[Example 1]: When the simple function is given
// Creating function name func1
function func1() {
}
// Creating function name func2
function func2(a, b) {
}
console.log("Name of the function func2 is: "
, func1.name)
console.log("Name of the function func2 is: "
, func2.name)
// Logging return type to console
console.log("Type of func.name is: "
, typeof (func2.name))
[Example 2]: When an object of function is given.
// Creating object of functions
let obj = {
function1: function functionName1() { },
function2: () => {
console.log("function2 is running")
},
function3: () => {
obj.function2();
},
}
obj.function3()
// Calling object function1 but function
// name is functionName1
console.log("Name of the function function1 is: "
, obj.function1.name)
console.log("Name of the function function3 is: "
, obj.function3.name)
[Example 3]: Using the name property on an instance of the function.
// Function func
function func() { };
// Obj is the instance of the
// function object func
let obj = new func();
if (obj.constructor.name === "func")
console.log("obj", obj,
"is an instance of function func")
else
console.log('Oops!')
[Example 4]: Using the name property on the bounded function.
// Function func
function func() { };
// Logging bounded function to console.
console.log("Name of the bounded func is: "
, func.bind({}).name)