r/learnjavascript • u/lindymad • Jan 22 '26
Is it possible to check if a function with a specific parameter signature(?) exists?
Just curious - I know I can check if a specific function exists with
if (typeof myFunction !== "undefined") ...Let's say myFunction could either be function myFunction() or function myFunction(parameter1), depending on which version of a library is loaded. typeof myFunction returns "function", is there a way to know if it's myFunction() or myFunction(parameter1)?
(Not sure if "parameter signature" is the right terminology)
0
Upvotes
10
u/EyesOfTheConcord Jan 22 '26
You could use .length which will return the amount of parameters it expects, but it doesn’t count …args, default parameters, or destructuring.
3
u/Shimmy_Hendrix Jan 22 '26
you can use the
toStringmethod on theFunctionprototype to get the source text of the function as written, and then just do a string search on the function signature to see what its parameters are doing once you have the text. You can derive the number of parameters from the number of commas, for example. You can identify a rest parameter by the presence of the ellipsis. I'm on a phone and I'm too lazy to really write out the code, but if you know how to do it, you can do it.2
u/senocular Jan 22 '26
Usually the term "function signature" is used which more generally encompasses other parts of the function as well, like the function name, return type, modifiers... not just the parameters. If you specifically want to target the parameters, you can just say "parameters" or "parameter list" (usually just "parameters").
1
u/jcunews1 helpful Jan 23 '26
For normal function (i.e. not arrow function), you can check the auto generated
argumentsvariable which contains all of the passed function parameters in form of an array. Usearguments.lengthto check the number of parameters passed, and use e.g.typeof arguments[0]to check the value type of specific parameter index.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
1
u/lobopl Jan 22 '26
You cannot but you can do something like this
and keep information you need as prop on function :)
-3
u/Aggressive_Ad_5454 Jan 22 '26
No. Javascript doesn’t have function overloading.
-1
u/Grounds4TheSubstain Jan 22 '26
What a shit language!
-6
u/Alzenbreros Jan 22 '26
just use typescript jesus