Sum All Numbers in a Range with recursion

Tell us what’s happening:
I passed this challenge with a for loop, but I wanted to make it a little shorter using recursion, but I’m trying to understand why it returns undefined.

The function alo by itself if it returns the desired value, but when I put that function into the sumAll function, it returns undefined.

I appreciate your help beautiful people.

Your code so far


function sumAll(arr) {

let startNum = arr[0];
let endNum = arr[1];

//if (startNum < endNum) {
  /*for (let i = startNum; i <= endNum; i++) {
    newArray.push(i);
  }*/
  return function alo(startNum, endNum) {
    if (startNum === endNum) {
      return startNum;
    }else{
      return startNum + alo(startNum + 1, endNum);
    }
  
  }/*else{
  for (let i = endNum; i <= startNum; i++) {
    newArray.push(i);
  }
  
  return newArray.reduce((acc, item) => {
    return acc + item;
  });
}*/
}

console.log(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/78.0.3904.108 Safari/537.36.

Challenge: Sum All Numbers in a Range

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

Look at the browser console instead of the Free Code Camp console. The FCC console is misleading. You are actually returning a function instead of the result of calling the function.

You just need to define the function within the sumAll function and then return the result of calling it the applicable arguments (startNum and endNum).

1 Like

This was my answer using recursion, I think it’s not the cleanest. I’m going to try it another way.

I don’t think I applied DRY.

function sumAll(arr) {
  let startNum = arr[0];
  let endNum = arr[1];

    if (startNum < endNum){
      function sumOfRange(startNum, endNum) {
        if (startNum === endNum) {
          return startNum;
        }else{
          return startNum + sumOfRange(startNum + 1, endNum);
        }
      };
      return sumOfRange(startNum, endNum);
    }else{
      function sumOfRange(startNum, endNum) {
        if (endNum === startNum) {
          return endNum;
        }else{
          return startNum + sumOfRange(startNum - 1, endNum);
        }
      };
      return sumOfRange(startNum, endNum);
    }
    
}

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

My suggestion is create a single sumOfRange function that either adds or subtracts 1 to/from startNum in the recursive call. Then, outside of the function after you have initialized startNum and endNum, swap the values of startNum and endNum based on either < or > (depending if you want to add or subtract 1 in the recursive call). Basically, the outer if statement should only determine what startNum and endNum should be and then return the call of sumOfRange.

1 Like