EN
JavaScript - get function name
7 points
In this article, we would like to show how to get function name in JavaScript.
Quick solution (use name
property):
xxxxxxxxxx
1
const myFunction = () => { // from now the arrow function will have `myFunction` as name
2
console.log('myFunction called...');
3
};
4
5
console.log(myFunction.name); // myFunction
Note: be careful using function names with transpilers or minifiers that may change function names.
In JavaScript we can create a function in few ways:
function myFunction() { }
const myFunction = function FunctionName() { }
const myFunction = function() { }
const myFunction = () => { }
Runnable code:
xxxxxxxxxx
1
function myFunction1() {
2
console.log('myFunction1 called...');
3
}
4
5
const myFunction2 = function FunctionName() {
6
console.log('FunctionName called...');
7
};
8
9
const myFunction3 = function() {
10
console.log('myFunction3 called...');
11
};
12
13
const myFunction4 = () => {
14
console.log('myFunction3 called...');
15
};
16
17
const variable1 = myFunction1;
18
const variable2 = myFunction2;
19
const variable3 = myFunction3;
20
const variable4 = myFunction4;
21
22
// Usage example:
23
24
console.log(myFunction1.name); // myFunction1
25
console.log(variable1.name); // myFunction1
26
27
console.log(myFunction2.name); // FunctionName
28
console.log(variable2.name); // FunctionName
29
30
console.log(myFunction3.name); // myFunction3
31
console.log(variable3.name); // myFunction3
32
33
console.log(myFunction4.name); // myFunction4
34
console.log(variable4.name); // myFunction4