# Need help with summing an array

Hi,

I’m working on a series of tasks in which I need to implement a function that takes 2 integers and returns the sum of every number between(and including) them. I wanted to use a spread operator to initially convert the function parameters into array and then use a loop to sum all the numbers between the min and max value. For some reason, it’s not working and it’s returning only the max value. Please help me figure out where’s the issue?

``````function sumAll(...numbers) {

let max = Math.max(...numbers);
let min = Math.min(...numbers);
let sum=0;
for (let i= min; i<=max; i++) {
sum =+ i;
}
return sum

}
sumAll (1, 4)

``````

The problem is in the above line. You’re post-incrementing, rather than pre-incrementing. Change `=+` to `+=`, and you should be fine.

EDIT: I’m exactly wrong. There is no `=+` - its reading that as `=`. I was thinking `++sum` vs `sum++`

1 Like

exactly. sum += i basically means just sum = sum + i

2 Likes

Right. But `sum =+ i` is taken by the js interpreter as “take this `i` thing, whatever it is, and coerce it into an integer (that’s what the `+` operator is doing there), then assign that value to `sum`.” Not adding, but overwriting.

1 Like

`sum =+ i` is the same as `sum = +i;`

By adding `+` in front you cast `i` as a number.

Example:
`let i = '1';`
`+x` // 1 (not a string)

1 Like
``````const sumAll = (lo, hi) => Array
.from({length: (hi - lo) + 1}, (_, i) => i + lo)
.reduce((a, b) => a + b);

sumAll(3, 8); // 33
``````
1 Like

Aaaah I see now. I feel very silly