function sumArgs() {
let sum = 0;
arguments.forEach((arg) => {
sum += arg;
});
return sum;
}
const result = sumArgs(1, 2, 3, 4, 5);
In JavaScript, arguments is not an array, it is an “array-like object” 😅. Because it’s an iterable, you can use a for loop to iterate over it, but if you want to use array methods like forEach, you need to convert it to an array first. There are a few different ways to do this.
function sumArgs() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
const result = sumArgs(1, 2, 3, 4, 5);
Or you can use the rest operator to get the arguments as an array:
function sumArgs(...args) {
let sum = 0;
args.forEach((arg) => {
sum += arg;
});
return sum;
}
const result = sumArgs(1, 2, 3, 4, 5);
Or you can use Array.from to convert the arguments to an array:
function sumArgs() {
let sum = 0;
Array.from(arguments).forEach((arg) => {
sum += arg;
});
return sum;
}
const result = sumArgs(1, 2, 3, 4, 5);