EN
JavaScript - get function argument names
7
points
In this short article we would like to show sinmple way how to get function argument names in 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.