Given a function and the task is to get the name of the function from inside the function using JavaScript. There are basically two methods to get the function name from within that function in JavaScript. These are:
- Using String substr() Method
- Using Function prototype name property
Get the Function name using String substr() Method
This method gets parts of a string, starting at the character at the defined position, and returns the specified number of characters.
Syntax:
string.substr( start, length )
Parameters:
- start: This parameter is required. It specifies the position from where to begin the extraction. The first character is at index 0. If start is positive and greater than or equal to the length of the string, this method returns an empty string. If start is negative, this method uses it as an index from the end. If start is negative or larger than the length of the string, start is used as 0.
- length: This parameter is optional. It specifies the number of characters to extract. If not used, it extracts the whole string.
Example: This example first converts the function to string using toString() method and then extracts the name from that string using substr() method.
Javascript
function functionName(fun) { let val = fun.toString(); val = val.substr( 'function ' .length); val = val.substr(0, val.indexOf( '(' )); console.log(val); } function GFGFunction() {} functionName(GFGFunction); |
GFGFunction
Get the Function name using Function prototype name property
This is a Function object’s read-only name property denoting the function’s name as defined when it was designed, or “anonymous” when created anonymously.
Syntax:
func.name
Return value: It returns the name of the function.
Example: This example gets the name of the function by using function proptotype name property.
Javascript
function functionName(fun) { let val = fun.name; console.log(val); } function GFGFunction() { } functionName(GFGFunction); |
GFGFunction