Languages
[Edit]
EN

JavaScript - get function name

7 points
Created by:
Lilly-Grace-Greig
211

In this article, we would like to show how to get function name in JavaScript.

Quick solution (use name property):

// ONLINE-RUNNER:browser;

const myFunction = () => {    // from now the arrow function will have `myFunction` as name
	console.log('myFunction called...');
};

console.log(myFunction.name); // myFunction

Note: be careful using function names with transpilers or minifiers that may change function names.

 

Practical example

In JavaScript we can create a function in few ways:

  • function myFunction() { }
  • const myFunction = function FunctionName() { }
  • const myFunction = function() { }
  • const myFunction = () => { }

Runnable code: 

// ONLINE-RUNNER:browser;

function myFunction1() {
	console.log('myFunction1 called...');
}

const myFunction2 = function FunctionName() {
	console.log('FunctionName called...');
};

const myFunction3 = function() {
	console.log('myFunction3 called...');
};

const myFunction4 = () => {
	console.log('myFunction3 called...');
};

const variable1 = myFunction1;
const variable2 = myFunction2;
const variable3 = myFunction3;
const variable4 = myFunction4;

// Usage example:

console.log(myFunction1.name);  // myFunction1
console.log(variable1.name);    // myFunction1

console.log(myFunction2.name);  // FunctionName
console.log(variable2.name);    // FunctionName

console.log(myFunction3.name);  // myFunction3
console.log(variable3.name);    // myFunction3

console.log(myFunction4.name);  // myFunction4
console.log(variable4.name);    // myFunction4
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join