DEV Community

Cover image for Javascript factorial

Javascript factorial

Ticha Godwill Nji on April 21, 2024

Hey everyone! I've stumbled upon this interesting JavaScript code that calculates the factorial of a number, and I'd love to hear your thoughts on...
Collapse
 
sakko profile image
SaKKo
const factorialMemo = {}
function factorial(n) {
  if (n === 0 || n === 1) {
    return 1;
  }
  if (!factorialMemo[n]) {
    factorialMemo[n] = n * factorial(n - 1)
  }
  return factorialMemo[n];
}
Enter fullscreen mode Exit fullscreen mode

For me, I would prefer to memoize the result. I'm not too worried about coding styles. As long as it is easy to read and it's correctly computed.

Collapse
 
ticha profile image
Ticha Godwill Nji

There are many coding styles and it is worth noting that one size doesn't fit all. So, it is totally ok to have your own coding style as long as the code follows the code practices and industry standards.

Collapse
 
sakko profile image
SaKKo

My point is just to improve performance.

Thread Thread
 
ticha profile image
Ticha Godwill Nji

I get it

Collapse
 
efpage profile image
Eckehard • Edited

You can use a simple loop, but recursion can be shorter:

   // Loop
    function fac1(n) {
      let k = 1
      for (let i = 1; i <= n; i++)
        k = k * i
      return k
    }

Enter fullscreen mode Exit fullscreen mode

With respect to your code: Why not check for (n <= 1) ? And this is a perfect case for the ternary operator, so your code could look like this:

    function factorial(n) {
       return (n <= 1) ?  1 : n * factorial(n - 1);
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ticha profile image
Ticha Godwill Nji

Smart thinking.

Collapse
 
efpage profile image
Eckehard

Thank you much!

Talking about improvements: else after return is superfluous. So, your unchanged code should look like this:

function factorial(n) {
    if (n === 0 || n === 1) 
        return 1;
    return n * factorial(n - 1);
}
Enter fullscreen mode Exit fullscreen mode

And your code is a bit dangerouse: see what happens, if you try factorial(-1). Checking for <=1 covers this too....

Thread Thread
 
ticha profile image
Ticha Godwill Nji

Thank you for pointing this out to me. It should cover negative numbers

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

๐Ÿ˜

// Loop
const fac = (n, k=1) => {for (;n--;k*=n+1){} return k}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ticha profile image
Ticha Godwill Nji

Smart thinking @jonrandy

Collapse
 
aminnairi profile image
Amin