Member-only story
In JavaScript, there are two ways to handle an indefinite number of arguments passed to a function: the arguments
object and rest parameters. Both serve a similar purpose, but they differ in syntax and behavior. In this article, we'll explore the differences between them and when to use each.
The Arguments Object
The arguments
object is a built-in object in JavaScript that contains all the arguments passed to a function, regardless of whether the function is defined with named parameters or not. It's an array-like object, meaning it has a length
property and can be accessed using array notation, but it lacks array methods like map
, filter
, and reduce
.
function sumNumbers() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
console.log(sumNumbers(1, 2, 3)); // Output: 6
console.log(sumNumbers(4, 5, 6, 7)); // Output: 22
In the example above, the sumNumbers
function doesn't have any named parameters, but it can still access the arguments passed to it using the arguments
object.