Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OK to invoke a JS function with more arguments than it formally receives?

Tags:

javascript

I have run across code that invokes a function as fn(a,b,c) but the definition of fn is fn(a,b) and then inside the author invokes arguments[2] which would imply a third undeclared argument. Is this legit? (I am new to the site and tried to search for a related question before posting, but was unable to find one. If there is a custom for doing so, I would love to be educated.) Thanks.

like image 819
Dave Avatar asked Dec 11 '25 04:12

Dave


1 Answers

It's allowed. It's usually better to specify good argument names and then check if they are null or not, for readability and sanity. People reading your code won't expect or understand that technique.

There are cases where it acceptable... for example:

function add(){
  var sum = 0;
  for (var i = 0; i < arguments.length; i++){
    sum += arguments[i];
  } 
  return sum;
}

However, even in this case it would be better to add placeholder variable names for the sake of readers:

function add(val1, val2, etc){
  var sum = 0;
  for (var i = 0; i < arguments.length; i++){
    sum += arguments[i];
  } 
  return sum;
}
like image 104
Lilith River Avatar answered Dec 12 '25 19:12

Lilith River



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!