Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JS offers the \'arguments\' object inside of functions to represent all passed a

ID: 647869 • Letter: J

Question

JS offers the 'arguments' object inside of functions to represent all passed arguments. Is there any broadly accepted concept for when/where this should be used?

I've seen items like this in the 'wild' that seem like code smell to me:

function myFxn () {
var myVar = arguments[0];
// do something with myVar
}
this is a very simplified example, but it illustrates what seems to me to be a poor coding practice. I would prefer

function myFxn (myVar) {
// do something with myVar
}
A colleague used it in a number of places where they only wanted to name the 'required' args ('required' by the implemenation ) but omit the 'optional' ones:

function myFxn (myReqVar) {
var myOptVar = (arguments[1] !== undefined) ? arguments[1] : false;
// do something with vars
}
This didn't seem wise on grounds of reduced readability and maintainability. It seems to me to create functions with confusing interfaces that must rely on the developer's knowledge of its intent or external documentation to understand and use.

Is this just a matter of opinion, or is there a preponderance of opinion on this?

Explanation / Answer

I think you are right, the best practice would be to use parameters over var paramName = arguments[0] . It is cleaner, easier to read and it shows the intent better. As a general rule of thumb the arguments object should be used over params under a few scenarios:

There can be N number of params:

function sum(){
var total = 0;
for (var i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
If you want to generically call other functions with the passed in arguments:

function other() {
otherFunction.apply(this, arguments);
}

vs

function other(arg1, arg2, arg3) {
otherFunction.call(this, arg1, arg2, arg3);
}