Open In App

How to get the function name from within that function using JavaScript ?

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:

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: 

Example: This example first converts the function to string using toString() method and then extracts the name from that string using substr() method




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);

Output
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




function functionName(fun) {
    let val = fun.name;
    console.log(val);
}
 
function GFGFunction() { }
 
functionName(GFGFunction);

Output
GFGFunction


Article Tags :