Languages
[Edit]
EN

JavaScript - get function argument names

7 points
Created by:
Giles-Whittaker
319

In this short article we would like to show sinmple way how to get function argument names in JavaScript.

getArgumentNames() usage example - JavaScript.
getArgumentNames() usage example - JavaScript.

Note: be careful, transpilation and compression may change argument names.

Practical example:

// ONLINE-RUNNER:browser;

const functionExpression = /^(?:function(?:\s+[^\(]+)?)?\(\s*([^\)]*\s*)\)/i;
const delimiterExpression = /,\s*/i;

const getArgumentNames = action => {
  	const code = action.toString();
  	const matching = functionExpression.exec(code);
  	if (matching) {
    	const group = matching[1];
      	return group.split(delimiterExpression);
    }
  	return [];
};


// Usage example:

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

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

const myFunction3 = function(arg1, arg2, arg3) {
	console.log('myFunction3 called...');
};

const myFunction4 = (arg1, arg2, arg3, arg4) => {
	console.log('myFunction3 called...');
};

console.log(getArgumentNames(myFunction1));
console.log(getArgumentNames(myFunction2));
console.log(getArgumentNames(myFunction3));
console.log(getArgumentNames(myFunction4));

Note: above example code doesn't wor for code with placed comments inside function declaration (e.g. function /* note ... */ myFunction() { }). It is necessary to do some preprocessing to remove comments.

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