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.

JavaScript

However, I am getting this error :

JavaScript

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.

JavaScript

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

JavaScript
Advertisement