Skip to content
Advertisement

– Write a function called sumNumbers that accepts a single array of numbers and returns the sum of the numbers in the array [closed]

I’m really new to JavaScript, So excuse me if this question might seem a little underwhelming.

I’m trying to write a function that performs the following:

1. accepts a single array of numbers and returns the sum of the numbers in the array. 2. If empty, returns 0.

let num3 = function sumNumbers([index]) {
if (index != "number") {
    return 0;
}
else {
    [index].reduce((a, b) => a + b, 0)
}


}



num3(1, 2, 3);

However, I am getting this error :

Uncaught TypeError: number 1 is not iterable (cannot read property Symbol(Symbol.iterator))
at sumNumbers (main.js:16:31)
at main.js:25:1

Anyone know the solution? would really appreciate it 🙂

Advertisement

Answer

You can iterate over the array using a for loop and increment the sum in each iteration and finally return it.

If there are no numbers in the array then the function would return the initial value of sum, which is 0.

function addNums(nums) {
  let sum = 0;
  for (let i = 0; i < nums.length; i++) {
    sum += nums[i];
  }
  return sum;
}

console.log(addNums([1, 2, 3]));
console.log(addNums([]));

You can also use Array.prototype.reduce and do the calculation in a single step.

const addNums = (nums) => nums.reduce((s, n) => s + n, 0);

console.log(addNums([1, 2, 3]));
console.log(addNums([]));
Advertisement