DEV Community

Calin Baenen
Calin Baenen

Posted on

How can I detect the presence of varargs in JS function?

When I did

function f(...args) {return args;}
f.length // 0
Enter fullscreen mode Exit fullscreen mode

And logged f.length, it showed 0.
Is there any way I can detect vararg parameters in JS?

Top comments (3)

Collapse
 
findoff profile image
abnessor aka findoff • Edited

Rest operator supports 0 or more args. Btw it's don't count as existing argument.
As i know, at this moment no ways to detect it other than toString().

function f(a, ...args) {return args;} // length count only real arguments
f.length // 1
f.toString() // "function f(a, ...args) {return args;}"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
atwright147 profile image
Andy Wright

Would you elaborate on what you are trying to achieve please?

Collapse
 
baenencalin profile image
Calin Baenen • Edited

I'm working on HotTea, and I'm creating an overloads function.

One of the things it has to do is check if there are methods with varargs parameters.
I want to check as a last resort, in case there are no overloads with X amount of parameters (where X is the amount of arguments you provide).

Something like this:

const add = overload("myFunction", [
  function add(x, y) {
    return x+y;
  }
  function add(x, y, z) {
    return (x+y)+z;
  }
];
Enter fullscreen mode Exit fullscreen mode

What it does internally is looks through this list and checks some criteria.
The criteria is:

  • The length is the same.
  • (If using typedOverload) The types match

If I check the list, I need to include the varargs (I may also need a distinct way of doing this).

Hopefully this helps explain my goals better.
Thanks. Cheers!