Decrement Not Passing Test in Recursion Exercises. Why?

Tell us what’s happening:

I don’t understand why decrement doesn’t work: (n–) doesn’t pass test, (n-1) does.

E.g., this works:

function sum(arr, n) {
  // Only change code below this line
  if (n <= 0) return 0;
  else return sum(arr, n-1) + arr[n-1];
  // Only change code above this line
}

This doesn’t:

function sum(arr, n) {
  // Only change code below this line
  if (n <= 0) return 0;
  else return sum(arr, n--) + arr[n--];
  // Only change code above this line
}

Your code so far


function sum(arr, n) {
// Only change code below this line
if (n <= 0) return 0;
else return sum(arr, n--) + arr[n--];
// Only change code above this line
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:84.0) Gecko/20100101 Firefox/84.0.

Challenge: Replace Loops using Recursion

Link to the challenge:

Hi there!

The decrement operator changes the value of n, so you have, in essence,

There are two things at work here.

First of all, the post decrement operator evaluates and then decrements. If you put the -- in front, it will decrement and then evaluate. It’s a subtle but occasionally very important difference.

Secondly, you are using it twice so it is performing that decrement twice. You could do else return sum(arr, --n) + arr[n]; and that would work, but would be difficult to read code.