Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to pass more arguments than the function declares? [closed]

Tags:

I have a function

function callback(obj){...} 

Is it okay to pass in more objects than were declared in the function signature? e.g. call it like this:

callback(theObject, extraParam); 

I tried it out on Firefox and it didn't seem to have a problem, but is it bad to do this?

like image 783
Kyle Avatar asked Mar 26 '10 17:03

Kyle


People also ask

What happens if you pass an extra parameter to a method in JavaScript?

JavaScript is extremely broad-minded about the number of arguments you pass to a function. If you pass too many, the extra ones are ignored. If you pass too few, the missing parameters get assigned the value undefined .

How many function arguments is too many Python?

Functions with three arguments (triadic function) should be avoided if possible. More than three arguments (polyadic function) are only for very specific cases and then shouldn't be used anyway.

How many arguments should a function have?

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.

What will happen if you call any function with more or less arguments than required in Python?

Passing many arguments will have no effect to the function, as long as the parameters are filled in.


1 Answers

JavaScript allows this, you can pass any arbitrary number of arguments to a function.

They are accessible in the arguments object which is an array-like object that has numeric properties containing the values of the arguments that were used when the function was invoked, a length property that tells you how many arguments have been used on the invocation also, and a callee property which is a reference to the function itself, for example you could write:

function sum(/*arg1, arg2, ... , argN  */) { // no arguments defined   var i, result = 0;   for (i = 0; i < arguments.length; i++) {     result += arguments[i];   }   return result; } sum(1, 2, 3, 4); // 10 

The arguments object may look like an array, but it is a plain object, that inherits from Object.prototype, but if you want to use Array methods on it, you can invoke them directly from the Array.prototype, for example, a common pattern to get a real array is to use the Array slice method:

function test () {   var args = Array.prototype.slice.call(arguments);   return args.join(" "); } test("hello", "world"); // "hello world" 

Also, you can know how many arguments a function expects, using the length property of the function object:

function test (one, two, three) {   // ... } test.length; // 3 
like image 58
Christian C. Salvadó Avatar answered Oct 07 '22 17:10

Christian C. Salvadó