Search code examples
javascriptrecursionfactorial

Factorialization in JavaScript only works with decreasing recursion, why?


The factorial function in JavaScript only works with decreasing recursion (i--). If I use i++ (Google Chrome), the function is invoked but no result is returned, almost as if I would have started an infinite loop. Where is the error in my code?

This code does not work:
function factorial(n) {
  if (n == 0 || n == 1) {
    return 1;
  }
  for (var i = 1; i < n; i++) {
    n *= i;
  }
  return n;
}

This code works:
function factorial(n) {
    for (var i = n - 1; i >= 1; i--) { 
        n *= i;
    }
    return n;
}

Solution

  • It happens due to the fact that in your for loop condition you are doing i < n comparison. n value is rising faster than i value (since n is multiplied in each iteration, while i is incremented) thus creating an infinite loop. You can fix that by using a different variable to store the result in:

    function factorial(n) {
      var r = n;
      if (n == 0 || n == 1) {
        return 1;
      }
      for (var i = 1; i < n; i++) {
        r *= i;
      }
      return r;
    }
    

    Described situation does not happen in the alternative version of your code (with decreasing iterator) because it's loop condition (i >= 1) does not use the n value that is being changed in each iteration.

    Also please bare in mind that neither of the two functions that you have posted are recursive. These are both iterative (first one with an increasing iterator, and the other - with a decreasing iterator).