3

On the question Get a function's arity it is presented the function.length property. But it does not work for function accepting rest parameters or a variadic number of arguments as function(...variable).

function func1() {}
console.log(func1.length);
// expected output: 0

function func2(...variable) {}
console.log(func2.length);
// expected output: 0

function func3(a) {}
console.log(func3.length);
// expected output: 1

How to know that the function func2 can accept a variable number of parameters? I cannot determine this just by using func2.length because it will say the function accepts 0 parameters while it "can" accept at least 0, 1 or more.

technophyle
  • 7,972
  • 6
  • 29
  • 50
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144
  • I'm not sure there is an easy way to know this programmatically. Your best bet would be to try and parse the source, I guess but it doesn't always work with functions that are derived from other functions. – VLAZ May 25 '20 at 16:08
  • *Every* function in JavaScript can accept a variable number of arguments. `func1(1, 'a')` just works. If you want to know what parameters a function has, which type and number of arguments it expects, and what it will do with them, you have to go read the documentation or code of the function. – Bergi May 25 '20 at 16:28
  • While they "can" accept, the function signature does not tell that explicitly they will be handled. Then, a function with `rest` parameter hints the caller that its extra arguments are probably expected and they can be handled. – Evandro Coan May 25 '20 at 16:30

0 Answers0