Languages
[Edit]
EN

JavaScript - get function source code

8 points
Created by:
Giles-Whittaker
319

In this article, we would like to show how to get source code for a given function in JavaScript.

Quick solution (use toString() on function):

// ONLINE-RUNNER:browser;

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

console.log(myFunction.toString());

Note: be careful using transpilers or minifiers that change function source code - code is optimized.

 

Practical example

// 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...');
};

// Usage example:

console.log(myFunction1.toString());
console.log(myFunction2.toString());
console.log(myFunction3.toString());
console.log(myFunction4.toString());
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