Reputation: 960
Let's say I have 300 functions in one script. Is it bad to access the arguments object within each function as opposed to passing in named parameters?
Edit: Okay a lot of you are asking why I would want to do this, it's really a theoretical question but since you asked is there any reason why i would want to do this, other than variable parameters?
Upvotes: 5
Views: 2748
Reputation: 147413
It is worth noting that strict mode affects the arguments object.
In non–strict mode, argument members are bound to their corresponding formal parameter (if a value has been passed), so changing the value of one changes the value of the other.
Not so in strict mode.
e.g.
foo('a');
function foo(arg) {
// Change the value of arg
arg = 'b';
arg == arguments[0]; // false in strict mode,
// true otherwise
}
Also, arguments.callee
and arguments.caller
are not available in strict mode. Attempting to access them will throw an error.
Upvotes: 0
Reputation: 707446
It is bad practice to write code that is hard to read and hard for others to understand, maintain or use.
It is good practice to specify named arguments and give them meaningful, useful, descriptive names whenever you can.
Also, you should remember that you can declare named arguments even if all are not required. You can then either test arguments.length
to see how many arguments were passed or test the values of the specific named arguments to see if they are undefined
or not.
In cases of highly variable arguments, you can also pass an object and let the object self-describe what arguments were passed.
There are specific cases when the arguments object is useful and when using it is the best way to write clear, concise and safe code, but I've never seen a case where all functions declare no named arguments and use only the arguments object. Unless you have some very unusual project, this would generally not be the best way to code for so many functions.
For performance, it appears that accessing named arguments is also faster than accessing the arguments object in all the major browsers. In this jsperf performance test that just sums the first three arguments passed to a test function, using the named arguments was 2-8x faster than using the arguments
object. The exact performance difference likely depends upon exactly what the function is attempting to do, but the arguments
object definitely looks slower.
If you provide more information on the reason why you want to use the arguments object instead of named arguments or why you think it would be beneficial to use the arguments object, then we might be able to offer more concrete advice.
Upvotes: 16
Reputation: 23863
In addition to jfriend00's excellent answer ...
Some of the modern Javascript engines[1] do not create the arguments
variable unless it is
eval
or similar constructThus, using arguments
can slow down a function simply by using it.
[1] V8 in Chrome, in particular.
Upvotes: 3