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...
For further actions, you may consider blocking this person and/or reporting abuse
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.
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.
My point is just to improve performance.
I get it
You can use a simple loop, but recursion can be shorter:
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:
Smart thinking.
Thank you much!
Talking about improvements: else after return is superfluous. So, your unchanged code should look like this:
And your code is a bit dangerouse: see what happens, if you try
factorial(-1)
. Checking for <=1 covers this too....Thank you for pointing this out to me. It should cover negative numbers
๐
Smart thinking @jonrandy