This post will discuss how to get the name of the current function being executed in JavaScript.

A function is a block of code that can be defined, invoked, and reused in a program. Getting the name of the current function means obtaining a string that represents the identifier or the expression that defines the function. Here are some of the methods that we can use to get the name of the current function being executed in JavaScript.

1. Using arguments.callee.name property

One way is to use the arguments.callee property, which is a reference to the current function being executed. We can use the name property of arguments.callee to get the name of the function as a string, or use arguments.callee.toString() and parse out the name from the function definition.

Download  Run Code

Output:

foo
bar
qux
Uncaught ReferenceError: arguments is not defined

 
However, this function is deprecated and forbidden in strict mode, as it can cause security and performance issues. It may also not work for anonymous functions or arrow functions.

2. Using Function.prototype.name property

The recommended option is to use the name property of the Function object, which returns the name of the function as a string. This property is more compatible with strict mode and works for named functions, either declared or assigned to a variable, but not for anonymous functions or arrow functions, as they do not have a name property.

Download  Run Code

Output:

bound foo
anonymous
foo
bar
qux
qux
foobar
foo
corge

3. Using Error.prototype.stack property

The Error.prototype.stack property returns the string representing the stack trace of an error object. This property can be used to get the name of the current function by creating an error object and parsing its stack property. However, it is not a standard property and may not be supported or consistent across different browsers or environments. Also, it may contain some extra information that needs to be filtered out to get the function name.

Download  Run Code

Output:

foo
bar
qux
foobar

That’s all about getting the name of the current function being executed in JavaScript.