What is wrong with this logic?Factorialize a Number

Tell us what’s happening:

Why won’t this work?

Your code so far


function factorialize(num) {
  for(let i=1;i<=num && i>0;i++){
  let newNum = num*num-i;
  return newNum;
  }
}

factorialize(5);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number

You are declaring the variable inside the loop and return it right after. Also your loop seems a bit confusing with an && operator.
i > 0 will always be true, so I dont know why you have that there?

I removed the i>0, and declared the variable outside. But i’m still not getting it.
Btw, when i run the test with 5, it returns 24

and this is the code given in the hint-

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

factorialize(5);

but I don’t understand why we should multiply num with factorialize(num-1)

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

factorialize(5);

but I don’t understand why we should multiply num with factorialize(num-1)

That’s a recursive pattern, so it’s calling itself and takes -1 off the num each time.
If num equals 0 it returns 1.
So it’s basically a loop within itself example) 5 * 5-1 * 4-1 * 3-1 * 2-1 * (1-1, equals 0, so will be 1).

You could do it that way, or with a for-loop and a variable outside the loop, which is a more basic approach.

function factorialize(num) {
  if(num === 0) return 1;
  let result = num;
  for(let i = 1; i < num; i++){
    result *= i;
  }
  return result;
}

Okay got it. thanks!