Reputation: 1911
I was looking at a javascript library and noticed that you can access arguments passed to a function using an arguments array like so...
function foo() {
var firstArg = arguments[0];
var secondArg = arguments[1];
//code
}
I had always done this by specifying parameters right in the function definition
function foo(firstArg, secondArg) {
//code
}
What are the advantages/disadvantages of these two strategies for reading function arguments?
Upvotes: 2
Views: 165
Reputation: 14768
If you identify your arguments, you won't have to declare variables for them and your code will be easier to understand.
The arguments array (it's not actually a real javascript array) can be useful if you may need a variable number of arguments. Like this:
function sum() {
var args = Array.prototype.slice.call(arguments); // turns the arguments array-like structure into a real array
var total = 0;
args.forEach(function(n) { total += n;});
return total;
}
Another use is in cases where you want to pass all of the arguments to another function without identifying them individually (which would be an issue if the functions parameters changed in the future or in cases of a variable number of arguments) such as:
function sumTimes3() {
return sum.apply(this, arguments) * 3;
}
Upvotes: 1
Reputation: 790
I always like to specify the parameters to my functions because it is more readable and clear. Particularly i don't like to use arguments[] because I don't know who is arguments or arguments[0].
But if i need to pass a lot of parameters to a function?
In this case a recommend, think about your function, it is probably breaking the concept of Single Responsibility Principle. And Read Clean Code book will help.
This is my opinion.
Upvotes: 1
Reputation: 141827
Usually you should use named parameters, the advantages being that you have less code and a more self-documenting function declaration.
The arguments object (it's not an array, though it is array-like) is useful if you do not know how many arguments your function will be called with. For example:
function sum () {
var result = 0;
for ( var i = 0; i < arguments.length; i++)
result += +arguments[i];
return result;
}
That function could be called as sum(1)
or sum(1,2,3,4,5)
.
Upvotes: 3
Reputation: 160191
The second names parameters explicitly, which aids in communications.
I almost never see the first method. It's more common to see an additional (named) parameter that takes an object with other parameters not explicitly named. IMO that would be highly preferred over accessing arguments
manually.
The benefit of accessing arguments
directly is that you don't need to do anything special to pass in an arbitrary number of parameters. The drawback is that you're now depending on positional parameters, which is essentially impossible to remember over time, particularly when there are several.
I see almost no real-world advantages to accessing arguments
except in rare cases.
Upvotes: 2