Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to understand recursion in JS… check my simple code

I am trying to wrap my head around recursive functions. I’ve tried a number of entry level exercises with no success. For example, I put this code into JS fiddle. I intended for it to take the sum of all numbers from 1 to n.

function sumAll(n) {
  if (n == 1 ) {
    return 1;
  } else if (n > 1) {
    return sumAll(n--) + n;
  }
}

console.log(sumAll(3));

feeding 3 to the function should give me ‘6’. I get an error, though.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The -- suffix operator will evaluate to the original value of n, and the subtraction from n will happen afterwards (which is also not desired as you still want to do + n). That means the recursive call gets the same value for n as the caller, and so you don’t get closer to the end…

Don’t use -- here, but -1:

function sumAll(n) {
  if (n == 1 ) {
    return 1;
  }
  else if (n > 1) {
    return sumAll(n-1) + n;
  }
}

console.log(sumAll(3));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading