The name
property returns the name of the function.
Example
// function definition
function greeting() {
console.log("Nice to meet you!");
}
// returns the name of the greeting() function
console.log(greeting.name);
// Output: greeting
name Syntax
The syntax of the name
property is:
func.name
Here, func
is a function.
name Parameters
The name
property does not take any parameters.
name Return Value
The name property returns the function's name as specified when it was created.
Note: If the function is created anonymously, the length property returns anonymous
or ''
.
Example 1: Using name Property
// function definition
function message() {
console.log("Hello World")
}
// returns the name of the message() function
console.log(message.name);
Output:
message
In the above program, we have defined a function named message()
. We are using the name
property to find out the name of the function that we have defined.
Using name
as message.name
returns the name of the function message()
i.e. message
.
Example 2: name Property for Anonymous Function
Anonymous function is a function that is created without a name.
We declare anonymous functions without using an identifier. We can create an anonymous function with new Function(..)
or Function(..)
syntax.
Using the name
property in an anonymous function returns anonymous
keyword. For example:
// name property for anonymous function
console.log((new Function).name);
// assigning anonymous function to a variable 'x'
const result = function() {
}
// using name property in the 'result' variable
console.log(result.name);
Output
anonymous result
In the above program, we have assigned an anonymous function to a variable named result.
The function is inferred as the variable name. So, using name
in result returns the variable name- "result".
Example 3: Using name Property in a Variable
// function definition
function func() {
}
// assigning the value of 'func' to a variable 'result'
let result = func;
// using name property in the 'result' variable
console.log(result.name);
Output
func
Here, we have assigned the value of func()
to a variable named result
. So result.name
returns the name of the func()
function i.e. func
.
Recommended Reading: JavaScript Function.length