Sum All Numbers in a Range - passes tests manually, but can't get past it

Sum All Numbers in a Range - passes tests manually, but can't get past it
0

#1

Hi,
can anyone help with this?
I have written code which should pass all the tests for the Sum All Numbers in a Range challenge, but FCC doesn’t recognise it.

var sum = 0;

function sumAll(arr) {
  arr.sort(function(a,b){
    return a - b;
  });
  for (var i = arr[0]; i<arr[1]+1; i++)
    sum += i;
  return sum;
}

sumAll([10, 5]);

I’m happy to rewrite my solution using the Math.max function as advised, but the above solution came to me pretty quickly and does the job nicely, so am wondering why the tests fail?

Any feedback appreciated!
Thanks
Colin


#2

You are using global variables.

Global variables persist after function calls have completed, so we have to be very careful about modifying globals in functions. Your code relies on sum being an 0 when the function is called, but after sumAll has been executed it is no longer 0. This means that your function will only work once.


#3

Thanks!
That sorted it.

I have a bit more reading to do it seems!