简体   繁体   中英

Var++ causes RangeError in recursive function parameter in JavaScript

I have a simple linear recursive function in JavaScript computing a factorial of a number.

function factorialImproved(n) {

  function factorialIter(p, c, m) {
    if (c > m) {
      return p;
    } else {
      return factorialIter(c * p, c++, m); // RangeError: Maximum call stack size exceeded // ++c or c+1 is OK
    }
  }

  return (factorialIter(1, 1, n))
}

I'm trying to figure out why I get RangeError with c++ but not with ++c or c+1 .

(c++) evaluates as c . So you are calling factorialIter with the same c every time.

Therefore, c = 1 won't be bigger than m = n unless n < 1 .

However, (++c) evaluates as c+1 . Just remember this rule:

  • (++c) : first increment then c .
  • (c++) : first c then increment.

In my opinion, you should be using c+1 . Do not use c++ or ++c unless you want to use c in that scope later.

You return the same value of c , because with postfix increment , it returns the actual value and then it increments the variable.

For getting a result, you could use just c + 1 as value. Or use prefix increment. But if you do not use the variable again, it is not advisable.

 function factorialImproved(n) { function factorialIter(p, c, m) { if (c > m) { return p; } else { return factorialIter(c * p, c + 1, m); // RangeError: Maximum call stack size exceeded // ++c or c+1 is OK } } return (factorialIter(1, 1, n)) } console.log(factorialImproved(5)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM