I noticed that in some functions the arguments object is used:
function fn(arg1, arg2)
{
console.log(arguments[0])
}
fn(1, 2); // 1
Why it is useful?
I noticed that in some functions the arguments object is used:
function fn(arg1, arg2)
{
console.log(arguments[0])
}
fn(1, 2); // 1
Why it is useful?
In your example, it's not useful and not a good idea. It can be useful when you want a function that can accept an indefinite number of arguments:
function sum() {
var total = 0;
for (var i = 0; i < arguments.length; i += 1) {
total += arguments[i];
}
return total;
}
console.log(sum(5, 6, 7, 8)); // 26
Note that ES6 allows the use of rest parameters which would be more useful in most cases where arguments
are used nowadays:
function sum(...values) {
return values.reduce(function (prev, cur) {
return prev + cur;
}, 0);
}