Is there a way to get the function parameter names of a function dynamically?
Let’s say my function looks like this:
function doSomething(param1, param2, .... paramN){
// fill an array with the parameter name and value
// some other code
}
Now, how would I get a list of the parameter names and their values into an array from inside the function?
Wow so many answers already.. Im pretty sure this gets buried. Even so I figured this might be useful for some.
I wasn't fully satisfied with the chosen answers as in ES6 it doesn't work well with default values. And it also does not provide the default value information. I also wanted a lightweight function that does not depend on an external lib.
This function is very useful for debugging purposes, for example: logging called function with its params, default param values and arguments.
I spent some time on this yesterday, cracking the right RegExp to solve this issue and this is what I came up with. It works very well and I'm very pleased with the outcome:
As you can tell some of the parameter names disappear because the Babel transpiler removes them from the function. If you would run this in the latest NodeJS it works as expected (The commented results are from NodeJS).
Another note, as stated in the comment is that is does not work with inlined arrow functions as a default value. This simply makes it far to complex to extract the values using a RegExp.
Please let me know if this was useful for you! Would love to hear some feedback!
Taking the answer from @jack-allan I modified the function slightly to allow ES6 default properties such as:
to still return
[ 'a', 'b' ]
I have modified the version taken from AngularJS that implements a dependency injection mechanism to work without Angular. I have also updated the
STRIP_COMMENTS
regex to work withECMA6
, so it supports things like default values in the signature.Here's one way:
Note: This only works on browsers that support
arguments.callee
.A lot of the answers on here use regexes, this is fine but it doesn't handle new additions to the language too well (like arrow functions and classes). Also of note is that if you use any of these functions on minified code it's going to go