JS Uncaught RangeError: maximum call stack size exceeded | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

JS Uncaught RangeError: maximum call stack size exceeded

Uncaught RangeError: maximum call stack size exceeded What does this mean? https://code.sololearn.com/W80juo0kJaPh/?ref=app

9th Nov 2018, 5:31 PM
Gordon
Gordon - avatar
4 Answers
+ 6
If you are trying to code a recursive function then you'll need a base case that stops the function to invoke itself, so your problem is that the factorial function will never end thus you are getting that error, try this if(n!=0) return n*factorial(n-1); else return 1; in this case the first option will be the recursive case that invokes the function only if n is diferent from 0 otherwise it will return 1 this being the base case and stopping the recursive function
9th Nov 2018, 6:33 PM
Oliver AF
Oliver AF - avatar
+ 2
Oliver AF is right but this kind of recursion still causes trouble in JS because it's not tail recursive. Because you do n*factorial(n-1), every call on the stack has to complete first before it actually starts calculating the product of n and factorial(n-1). This way, the call stack just keeps growing all the time and at higher numbers you quickly get a "maximum call stack size exceeded". The new JS V8 engine can optimize for tail call ercursion. In order to make this function tail call recursive you could accept n as an extra parameter in the function itself. So instead of returning n*factorial(n-1) you return factorial(n, n-1). This way no computation has to be done on the result of your function call and the stack doesn't keep growing. Edit: here's a tail recursive version: function factorial(n, a = 1) { if(n === 0) return a; return factorial(n - 1, n * a); } you can just call this as factorial(n) and a will get a default value of 1 in the first call.
10th Nov 2018, 7:41 AM
Brendon Bosman
Brendon Bosman - avatar
+ 2
Thanks Oliver and Brendon
10th Nov 2018, 10:37 AM
Gordon
Gordon - avatar
0
i have the same problem with factorial with a big number , I need to calculate the probability Cn,k = n! / k!(n-k)! but i have this error with the factorial function, even when i tried with this : function factorial(n, a = 1) { if(n === 0) return a; return factorial(n - 1, n * a); } undefined factorial(200000) VM617:1 Uncaught RangeError: Maximum call stack size exceeded at factorial (<anonymous>:1:19) at factorial (<anonymous>:3:12) at factorial (<anonymous>:3:12) at factorial (<anonymous>:3:12) at factorial (<anonymous>:3:12) at factorial (<anonymous>:3:12) at factorial (<anonymous>:3:12) at factorial (<anonymous>:3:12) at factorial (<anonymous>:3:12) at factorial (<anonymous>:3:12)
19th Jun 2020, 11:57 AM
am consultantdev
am consultantdev - avatar