Sum All Numbers in a Range - Have a little issue here

Tell us what’s happening:
The code below is not working but when I remove the ‘else if’ condition it works.
I want to know why is it so?
The ‘else if’ condition doesn’t even in use for the given test cases.
So, what’s the problem here?
( I know that the ‘else if’ condition is wrong but still if it is not even coming in use for the given test cases why does it hold some test cases?)

Your code so far


function sumAll(arr) {
  let sum = arr[arr.length-1];
  if(arr[0] < arr[arr.length-1]) {
    for(var i = arr[0]; i < arr[arr.length-1]; i++) {
        sum = sum + i;
    }
  }
  else if(arr[0] = arr[arr.length-1]) {
    sum = arr[0];
  }
  else {
    sum = arr[0];
    for(var i = arr[arr.length-1]; i < arr[0]; i++) {
        sum = sum + i;
    }
    
  }
  
  return sum;
}

sumAll([1, 4]);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range

I’m not sure what you mean.
If you remove the following, your solution works:

  else if(arr[0] = arr[arr.length-1]) {
    sum = arr[0];
  }

This is not a comparison. It is an assignment. Almost all values are truthy, so this most often than not is evaluated as true and the statement is executed

1 Like