# Sum Numbers in a range

Hello, I just solved the sum all numbers in a range challenge but I got a strange behavior in the process

I first did this…

``````var total = 0;
function sumAll(arr) {
var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);

for(var i = min; i <= max; i++){
total += i;
}

}
sumAll([5, 10]);
``````

only the first test that checks if the output is a number passed, though the outputs were correct. However, when I did the following, which is basically changing the scope of the total variable, it was accepted

``````function sumAll(arr) {
var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);
var total = 0;

for(var i = min; i <= max; i++){
total += i;
}

}
sumAll([5, 10]);
``````

WHY???

The reason the first one fails on the other tests is because the total variable is declared globally so it each time the function is called, it is not reset to 0 (like the 2nd version does).

See what happens in the following link:

1 Like

This is what I did. It works.

``````function sumAll(arr) {
var sum = 0;
if(arr>arr){
for(var i = arr; i <= arr; i++){
sum = sum + i;
}
}
else{
for(var j = arr; j >= arr; j--){
sum = sum + j;
}
}
return sum;
}

sumAll([4, 1]);
``````

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. congrats.I will try with this later.

### I am wandering if there is a way to create the numbers without using for.....

I mean for example using map. Because as I understood map method return an array with the same input length.....

``````function sumAll(arr) {
let data = ([].concat(arr)).sort((a,b)=>a-b);
let newData = []

for (let i = data;i<=data;i++){
newData.push(i)
}
return(newData.reduce((a,b)=>a +b));

}

sumAll([1, 4]);
``````

There is also a mathematical formula for adding all numbers from X to Y, which is very useful here, and lets you avoid a for loop completely.

``(highestNumber - lowestNumber + 1) * (highestNumber + lowestNumber) / 2``

aww wow… that’s genius i understood ur solution perfectly. good job!