freeCodeCamp Challenge Guide: Sum All Numbers in a Range Bug

This challenge contains a bug and I have the solution for it.

I use this solution and shouldn’t get a “success” message.

function sumAll(arr) {
  if(arr.length>2){
    return -1;
  }

  let sum=0;
  if(arr[0]>arr[1]){ 
    for(let i=arr[0];i>=arr[1];i--){
      sum+=i;
    }
  }
  else{
    for(let i=arr[0];i<=arr[1];i++){ 
       sum+=i;
    }
  }

  return sum;
}

console.log(sumAll([4, 1])); //10
console.log(sumAll([1, 4])); //10
console.log(sumAll([5, 10]));//45
console.log(sumAll([4, 4])); //4 Ooops Bug here! 

So if you do a check with an array with the same numbers, the bug is solved.

Can you give link to the challenge please?

why that shouldn’t give you success?

You have a bug in your code for this case.

The challenge asks “Return the sum of those two numbers plus the sum of all the numbers between them
So the last console.log should return me a 8 and not 4

console.log(sumAll([4, 4]))

I didn’t said any different

I misread the else condition - I don’t see why this would be a bug. That code meets the requirements. The wording of the requirements is slightly awkward but the last console log most certainly should not give you 8 - the sum of all numbers between 4 and 4 is definitely 4.

The challenge says " Return the sum of those two numbers plus …"

You have a good point here. Sounds like we should update the instructions because the original intent here was not to sum the 4 and 4 in a case like this.

Maybe the instructions could read as follows:

We’ll pass you an array of two different integers. Return the sum of those two integers plus the sum of all the integers between them. The lowest number will not always come first.

This way we never have to worry about adding the test case of [4, 4] because the requirements are the two integers will always be different.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.