Trying to understand recursion in JS… check my simple code

Advertisements

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.

>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));

Leave a Reply Cancel reply