How to figure out the number of parameters in the passed callback function?

Viewed 54

When using a 3rd party library I often find an optional parameter in the callback.

For example, in Mocha when the callback done parameter exists, it waits for done to be invoked before moving on to another test case.

someFunction(function(done) { /** code **/ })
someFunction(function() { /** this behaves differently than above **/ })

How can I achieve the same behavior?

1 Answers

You can check the length attribute of the function object

console.log((()=>42).length);    // 0
console.log(((x,y)=>42).length); // 2

note however that you cannot be sure of exactly how many the function is going to access, because it's also possible to use arguments inside Javascript non-arrow functions and "rest" parameters inside arrows (that are not counted in .length attribute).

Related