modeller modeller - 1 year ago 73
jQuery Question

Why it works if I pass in a no-param function as callback expecting arguments?

I have been using this feature often: in

$.each(Ojbect, function)
, the function should expect for two arguments:

function (index, value) {...}

(per jQuery API document: enter link description here). Most of the time, I define my a non-arg function. For-example, to print out the value only.

$.each([1,2,3], function(){

So the $.each is accepting my no-arg func. This comes very handy in daily use. But I have not found any official document that says this is OK. Just to be assured in mind, why such way works?

Answer Source

That is how JavaScript function calls work. The number of arguments passed in to a function doesn't need to match the number of parameters in that function's definition. If there are less parameters than arguments (like in your example), the arguments will still be accessible, within the function, through the arguments array-like object. If there are more parameters than arguments, the variables without matching arguments will be undefined:

 function(){ console.log( arguments ); },     // ['foo', 'bar']
 function(x){ console.log( x, arguments ); }, // 'foo' ['foo', 'bar']
 function(x,y){ console.log( x, y ); },       // 'foo' 'bar'
 function(x,y,z){ console.log( x, y, z ); },  // 'foo' 'bar' undefined

// Call each function with two arguments: 'foo' and 'bar'
forEach( func => func( 'foo', 'bar' ) );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download