0

The exercise wants you to make a function that will take an integer and go through adding up its total - 1 each time, so i.e. 4 would be 4 + 3 + 2 + 1 = 10

function addUp(num) {
  if (num === 1) return 1;
  return num + addUp(num - 1);
}

This works, but I'm not sure how. If I used say 6 to me the return line would be 6 + 5 = 11; I'm not sure how this looping? Thanks

  • 1
    "Recursion" is the word you should be researching. Good luck! – brian Apr 12 '21 at 15:29
  • 2
    Make use of the debugger in your browser's developer tools. Step through the code line and by and watch what is happening. – Quentin Apr 12 '21 at 15:29
  • This is classic recursion like the factorial exercise, but subtracting instead of multiplying. The function is calling itself with one less than it was called with, until it gets down to 1, then it bubbles back up the stack. – Nikki9696 Apr 12 '21 at 15:30

0 Answers0