Quick question about code

function factorialize(num) {
  if (num === 0) { 
    return 1; 
  }
  return num * factorialize(num-1);
}

factorialize(5);

or

function factorialize(num) {
  if (num === 0) { return 1; }
  return num * factorialize(num-1);
}

factorialize(5);

Is there a difference? Which is preferred?

Is there a difference?

Not really Just white spaces are removed.

Which is preferred?

I’d prefer 1st one as it has proper indentation and is more readable.


There is, however, a non recursive version. By using loops

function factorialize(num) {
  var factorial = 1;
  for(var i=1;i<=num;i++){
    factorial *=i;
  }
  return factorial ;
}

factorialize(5);

What you do is, you run a loop from 1 (not 0, because anything multiplied by 0 is 0) to i<=num (because you need to include original number as well) or to i < num+1. (for the same boundary condition).

Then inside the loop, you multiply your factorial value with i and return factorial value after loop ends.

Which is preferred?

It really depends on you. For most people recursion is not intuitive.

Thanks for the quick and easy to understand reply, helps a lot! :heart_eyes:

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

Why am I not allowed to edit the code? Do I need to be a mod or do i need to acquire enough points? How does this work?

You can only edit your own posts unless you’re a mod. There isn’t really a point system in the forum, but there are trust levels (see the Trust Level badges).

1 Like

There is absolutely no difference. I prefer the second one. It’s more concise and readable.

I think this is probably best:

function factorial(num){
  return num === 0 ? 1 : num * factorial(num--);
}