In JavaScript, you can design a sum() function that accepts any number of arguments using the rest parameter.
Here are three different patterns to compute the total:-
- Using a for Loop (Traditional Method)
function sum(...args) {
let arr = [...args];
if (arr.length <= 0) return 0;
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log(sum);
}
sum(3, -4, 5);
- Using map() Method (Less Common but Works)
function sum(...args) {
let arr = [...args];
if (arr.length <= 0) return 0;
let sum = 0;
arr.map((val) => (sum += val));
console.log(sum);
}
sum(3, -4, 5);
- Using reduce() (Best & Cleanest)
function sum(...args) {
let arr = [...args];
if (arr.length <= 0) return 0;
const total = arr.reduce((acc, curr) => acc + curr, 0);
console.log(total);
}
sum(3, -4, 5);
Final Thoughts
- for loop → good for beginners
- map() → not ideal for summing
- reduce() → clean, functional, professional approach
Top comments (0)