Sum All Numbers in a Range why won't this work?

Tell us what’s happening:
I’ve created a new variable, sum, initialized to 0. I sorted the array from low to high with the sort method. I ran a for loop and initialized i to the arr[1], and worked down to arr[0]. The loop does not seem to be adding i to the sum. I can’t figure out the reason for this. I would greatly appreciate if someone could give an explanation for this.

Your code so far

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

sumAll([4, 9]);

Your browser information:

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

Link to the challenge:

Check the condition in the for-loop. It never evaluates to true, so it never runs.

Why do you sorting array?

Thanks @kevcomedia, Needed a > , not a < .

@0Prime The problem requires you to solve arrays where the larger number comes before the smaller number. There’s probably a way you can solve the problem without sorting, but the way I set up my for loop required me to first sort the array from smallest to largest number.

You can use Math.max() and Math.min() to get the smaller and larger numbers.

@kevcomedia oh right, I see where you are going with that. Set i = Math.max(arr) and so on. Yeah, definitely a better way to solve the problem.

@kevcomedia @0Prime thank you two for taking a look over my code. :handshake:

It’s a good solution when you only need either max or min number. When you want both - it’s easer just sort them:

const [min, max] = pair.sort()
// instead of:
const min = Math.min(...pair)
const max = Math.max(...pair)

…except JS treats array contents as strings by default when sorting, and I find writing the sort function callback cumbersome just to sort two numbers. I find the min and max more straightforward, but to each their own!