Can someone help explain what I'm doing wrong?

I’m a beginner and still don’t understand a lot about JavaScript but I feel like my code here should work.
I’m wondering why it just returns 0 for the sum.

My Solution:

``````function sumAll(arr) {
var sum = 0;
var min = Math.min(arr);
var max = Math.max(arr);
var i = min;
while (i <= max) {
sum += i;
i++;
}
return sum;
};

console.log(sumAll([1, 4]));
``````
``````  **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36`.

Challenge: Sum All Numbers in a Range

I’d take a look at the examples here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min

You should pass an array into `Math.min()` and `Math.max()` a little bit differently than you are.

1 Like

(…arr)
It worked! thanks!
Is there a reason I need to incorporate the spread operator?

The min and max function just aren’t designed to work on arrays like that. Those particular functions expect a comma separated list of arguments rather than an array holding the arguments.

1 Like

So any time I pass an array into a min/max function I need to use the spread operator?

In my opinion that’s the cleanest approach. There are some other ways, but they are a little bit more verbose.

Here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max#getting_the_maximum_element_of_an_array
they list a couple of other ways to do it.

1 Like

You don’t have to use the spread operator. It is just one way of taking an array of numbers and converting it into arguments to pass to the functions. You should be aware of the other approaches as some older browsers do not support the spread operator.

1 Like

Great, thanks for your prompt assistance! Wasn’t expecting help immediately lol

1 Like