Sum all Numbers in a range challenge won't complete but the results match

Sum all Numbers in a range challenge won't complete but the results match
0.0 0

#1

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

}
return result;

}

sumAll([3,7]);

Please help guys :slight_smile:


#2

It doesn’t like the fact that result is declared outside of your function.


#4

Yeah thanks guys, it worked now. :slight_smile:
But is it wrong to declare my variable outside of the function?


#5

You want to reduce your variables’ visibility as much as possible. That way only parts of your code that really need that variable can access it (and you can avoid accidentally altering its value via other parts of your code that don’t need it).


#6

It is not wrong per se, the problem is caused because FreeCodeCamp

run multiple test cases in on the code, using a global var like this persists the last value and hence the test cases fail.