Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
- Write a function called sumNumbers that accepts a single array of numbers and returns the sum of the numbers in the array

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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([]));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!