DEV Community

Discussion on: Find the factorial of a number in JavaScript

Collapse
 
chidioguejiofor profile image
Chidiebere Ogujeiofor • Edited

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:


const factorial = (n, currentProduct=1) => {
  //base case 1: return -1 if the number is less than 0
  if (n < 0) return -1
  //base case 2: return 1 if the number is 0
  if (n === 0) return currentProduct;
  //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 completely
  return factorial(n-1, n* currentProduct); 
}

factorial(6);

Explaining this briefly and in simple terms is quite hard but Anjana Vakil & Natalia Margolis in this video explained it superbly.

Collapse
 
master_elodin profile image
Alexander Oguejiofor

Thanks for pointing that out. Will definitely check out the video.