DEV Community

Dharmesh
Dharmesh

Posted on

3 Ways to Create a Sum Function in JavaScript

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:-

  1. 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);

Enter fullscreen mode Exit fullscreen mode
  1. 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);

Enter fullscreen mode Exit fullscreen mode
  1. 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);

Enter fullscreen mode Exit fullscreen mode

Final Thoughts

  • for loop → good for beginners
  • map() → not ideal for summing
  • reduce() → clean, functional, professional approach

Top comments (0)