0

first post so I'm trying to follow the rules here best I can. I'm trying to write a simple function that uses recursion to return the sum of all numbers between 1 and num. I've seen the solution to this, and I get how it works, but I don't get why THIS solution doesn't work. Any feedback is appreciated.

const sumNums = (num) => { 
  let total = 0;
  if(num >= 1) {
    total += num;
    sumNums(num-1);
  }
  return total; 
}
console.log(sumNums(5)); // <-- returns 5

1 Answers1

-1

Your particular solution doesn't work because you don't return stuff in your if branch. You only have one return and that's why you get what you pass in parameter. You also need to add up that inner calls in order for it to work.

Proper solutions are already in here.

EDIT: I just noticed you explicitly wanted to do recursion, here's a snippet with (tail) recursion.

function sumNumsTailRec(n, acc = 0) {
    if (n === 0) return acc
    return sumNumsTailRec(n-1, acc + n)
}
Jakub Žitný
  • 962
  • 1
  • 9
  • 38