One interesting thing I could add though is that modern JS engines can optimize your recursive function if they are Tail Call Optimized. This could make them to actually run forever without throwing the maximum recursion error.
You do this by ensuring that your recursive call is the very last operation that occurs in your function thus making the local variable disposable.
Making a slight change to your recursive solution could achieve this:
constfactorial=(n,currentProduct=1)=>{//base case 1: return -1 if the number is less than 0if(n<0)return-1//base case 2: return 1 if the number is 0if(n===0)returncurrentProduct;//else call the recursive case// there is really no need to wait for the result of this function call // thus all this stack can be removed completelyreturnfactorial(n-1,n*currentProduct);}factorial(6);
Nice article short and sweet.
One interesting thing I could add though is that modern JS engines can optimize your recursive function if they are
Tail Call Optimized
. This could make them to actually run forever without throwing the maximum recursion error.You do this by ensuring that your recursive call is the very last operation that occurs in your function thus making the local variable disposable.
Making a slight change to your recursive solution could achieve this:
Explaining this briefly and in simple terms is quite hard but Anjana Vakil & Natalia Margolis in this video explained it superbly.
Thanks for pointing that out. Will definitely check out the video.