Used if else is that wrong

Tell us what’s happening:

Your code so far


function sumAll(arr) {
  if (arr[0]<arr[1]){
  for (var element=arr[0]; element<=arr[1]; element++){
    var sum = 0;
    sum += element;
  }
  return (sum);
  }else{
     for (var element=arr[0]; element>=arr[1]; element--){
       var sum = 0;
       sum += element;
     }
     return (sum); 
  }
}

sumAll([5,10]); //


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 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/

Do you have a question?

So, just brainstorming here – I’m assuming you’re getting an error about redeclaring a variable over and over again – because every time you loop, you re-declare sum and set it to zero. Doing so, if the js engine were to allow it, would exit the loop with sum equal to the final value of that loop.

Move the var sum = 0; to the top of the function, outside of both for loops. Then, as @ArielLeslie suggested, c’mon back with a question.

1 Like

It should return the sum of those two numbers plus the sum of all the numbers between them. But I am trying with if else and its not giving me the result. Where did i go wrong.

Fixed that and it worked and thank you:grinning:

2 Likes