0

This code works:

function factorial(n){
  if(n==0){
   return 1;
  }else{
   return n* factorial(n-1);
  }
};

console.log(factorial(5));

This doesn't:

function factorial(n){
  if(n==0){
   return 1;
  }else{
   return n* factorial(n--);
  }
};

console.log(factorial(5));

I was working on a simple challenge 'factorial' using recursion. can someone explain to me why I have to use 'n-1' and when I use 'n--' it gives me 'RangeError: Maximum call stack size exceeded.'?

user2864740
  • 60,010
  • 15
  • 145
  • 220
pasha
  • 51
  • 6

2 Answers2

2

If you used

return n* factorial(n--);

what that does is it decrements n, and the n-- expression evaluates to the value of n before the decrement. This is called post-decrement.

let n = 3;
console.log(n--);

While you can use

return n* factorial(--n);

called pre-decrement, which will decrement n and have the expression evaluate to the value of n after the decrement, there's no sense in reassigning n at all here - you don't access it after the recursive call, after all. (the n* that comes before the recursive call has already been evaluated, but changing n while calling the recursive function looks like an easy source of confusion.) Calling factorial with n - 1 makes the code's intent more clear, and so should be preferred:

return n* factorial(n - 1);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-1

You need the '--' in front of the variable or the code executes it after the variable is passed

function factorial(n){
  if(n==0){
   return 1;
  }else{
   return n* factorial(--n);
  }
};

console.log(factorial(5));
Cody Swann
  • 637
  • 6
  • 9