You can create a function that calculates the sum of any number of arguments using the arguments object, rest parameters, or array methods.
1️⃣ Using Rest Parameters (ES6)
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
// Example usage
console.log(sum(1, 2, 3, 4)); // 10
console.log(sum(5, 10, 15)); // 30
Explanation:
...numberscollects all arguments into an arrayreduceiterates over the array and sums the elements
2️⃣ Using the arguments Object (ES5)
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
// Example usage
console.log(sum(1, 2, 3, 4)); // 10
console.log(sum(5, 10, 15)); // 30
Explanation:
argumentsis an array-like object containing all passed arguments- Use a loop to sum all values
3️⃣ Using apply with Math.sum Pattern
function sum() {
return Array.prototype.reduce.call(arguments, (a, b) => a + b, 0);
}
console.log(sum(2, 4, 6)); // 12
- Converts
argumentsinto an array usingArray.prototypemethods
⚡ Key Points:
- Prefer rest parameters (
...args) in modern JS - Works with any number of arguments
- Handles 0 arguments gracefully (
sum()→0)