I’ve noticed that sometimes when I’m passing a callback function in jQuery, I can get away with not having the function specify all the parameters.
For example, in the .each() function, it takes a function which has parameters index,Element. However you can use give it fewer parameters than that as evident in the first example in the documentation: $('li').each(function(index){...}.
When is this valid? And why is this syntactically valid?
What jQuery does is examine the type of the parameters you passed and figures out what you meant. That gives you some flexibility in what you include. This only works when the expected parameters are a different type. For example, if you have three possible parameters for a function: a string, a number and a function, then the receiving function can examine the type of each parameter and figure out which is which no matter what order they are passed in or which ones are included.
In jQuery, there is usually only one parameter that’s a function so, jQuery can pretty much find it no matter where it is in the parameter list.
If, on the other hand, the function took two strings or two functions as parameters, then those would have to be passed in the right order so the receiving function could know which was which.
This can work in javascript because:
If you look at the click() function, you see jQuery has three possible ways to use it:
Internally, the click function in jQuery is declared like this:
Then, when that function is called jQuery looks at the parameters data and handler and determines that if both parameters are undefined, then the caller must have done:
If only the handler parameter is undefined and the data parameter is defined and is a function type, then the caller must have used the second form of:
In this case, jQuery internally does this to put the parameters into the right slots before using them:
If both parameters are not undefined, then the caller must have used:
and it can use both parameters as declared.