I wonder if it is possible to show a library user that a function needs a callback with let’s say 5 parameters 3 of which are arrays (for example).
Or in other words, how to inform the programmer not to mess up with the callback arguments?
Here’s a code example:
function doSomething(someArray, callback) {
var i = 0;
for ( i = 0; i < someArray.length; i += 1) {
callback(someArray[i]);
}
}
How a programmer would find out what parameters should their callback function accept?
Javascript does not have type checking for arguments and there is no way for you to do runtime checking of a callback to see what arguments it is expecting. One thing you can do at runtime is you can check
callback.lengthto see how many arguments it has declared that it is expecting as formal parameters. It is not required for a function to define it’s formal parameters as it can also use the arguments object to get the arguments, but if you wanted to force them to program a certain way, you could check it this way. See this doc for more info.Your best option is good documentation to make it absolutely clear (often with sample code too) how a callback should be written.
If you want to bulletproof your library a bit, you could catch any exceptions that were thrown in the callback and handle them however is appropriate.