Get Function Parameter Names Dynamically in JavaScript
In JavaScript, you can extract the parameter names of a function dynamically using string manipulation. This is useful for debugging, code analysis, or building custom frameworks that inspect functions at runtime.
- JavaScript toString() method converts a function into its string representation.
- You can extract parameters by isolating text between
(and). - Regular expressions help remove comments, function bodies, and extra spaces.
- Works with both regular functions and arrow functions.
[Approach]: Using toString() and Regex
JavaScript contains a method called toString() which is used to represent a function code in its string representation. This method is used to get the parameter names/values.
- First, get the function's code to its string equivalent using toString() method.
- Then remove all the unnecessary codes like comments, function body, white spaces, and ES6 arrow (if any).
- Identify the first occurrence of '(', it will be just before the starting of parameters.
- The last character of the string will be ')' which removes all comments, function body, white spaces, and ES6 arrow.
- Also, the last character will be just after the end of the parameters.
// JavaScript program to get the function
// name/values dynamically
function getParams(func) {
// String representation of the function code
let str = func.toString();
// Remove comments of the form /* ... */
// Removing comments of the form //
// Remove body of the function { ... }
// removing '=>' if func is arrow function
str = str.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/\/\/(.)*/g, '')
.replace(/{[\s\S]*}/, '')
.replace(/=>/g, '')
.trim();
// Start parameter names after first '('
let start = str.indexOf("(") + 1;
// End parameter names is just before last ')'
let end = str.length - 1;
let result = str.substring(start, end).split(", ");
let params = [];
result.forEach(element => {
// Removing any default value
element = element.replace(/=[\s\S]*/g, '').trim();
if (element.length > 0)
params.push(element);
});
return params;
}
// Test sample functions
let fun1 = function (a) { };
function fun2(a = 5 * 6 / 3,
b) { };
let fun3 = (a, /*
*/
b, //comment
c) => /** */ { };
console.log(`List of parameters of ${fun1.name}:`,
getParams(fun1));
console.log(`List of parameters of ${fun2.name}:`,
getParams(fun2));
console.log(`List of parameters of ${fun3.name}:`,
getParams(fun3));
Output
List of parameters of fun1: [ 'a' ] List of parameters of fun2: [ 'a', 'b' ] List of parameters of fun3: [ 'a', 'b', 'c' ]
Advantages
- Helps inspect and document functions automatically.
- Useful for debugging and testing dynamic code.
- Works without executing the function.