DEV Community

Alexander Oguejiofor
Alexander Oguejiofor

Posted on

Find the factorial of a number in JavaScript

The factorial of a natural number in mathematics is defined as that number multiplied by that number minus one, then that number minus two, and so on until that number gets to 1. Ergo, if we choose to represent the number with the letter n, the factorial will be the product of all the positive integers less than or equal to n. The factorial of a number n is often denoted as n!

For example:

n! = n * (n - 1) * (n - 2) * …*1
4! = 4 * 3 * 2 * 1 = 24

The Challenge

Write a function that returns the factorial of a number n.

Here, I will explore two approaches.

The recursive approach

Keeping in mind that the factorial of a number can be computed by finding the factorial of that number - 1 and then multiplying the result with the number. The factorial of the number - 1 is a subproblem that needs to be solved first, so we compute that again and again (recursively).

const factorial = (n) => {
  //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 1;
  //else call the recursive case
  return n * factorial(n - 1);
}

factorial(6) //--> 720

This solution has greater memory requirements as all the function calls would remain on the call stack until it gets to the base case.

Computing iteratively...

The input n is decremented gradually until it gets to 1. In each iteration, a result variable is updated with the value of multiplying the result with the current value of the input.

const factorial = (n) => {
  //create variable to save final result
  let res = n
  // if input = 0 or input = 1, return 1
  if (n === 0 || n === 1) return 1
  //initialize loop; should run wile num > 1
  while (n > 1) {
    n-- //decrease num by 1 with each iteration
    res = res * n //update result by multiplying with decreased num
  }
  //return the computed factorial of the input
  return res
}

factorial(6) //--> 720

The upside of this approach is that it takes less memory than the recursive implementation at the cost of writing a bit more code.

We've now examined two ways to find the factorial of a number in JavaScript. Both implementations are okay and could help you pass that coding challenge.

Top comments (2)

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.