Making sure I understand recursion

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

factorialize(5); 

I always find it easier to understand if I try explaining it to someone else. I just finished the “Factorialize a Number” on algorithm scripting and I want to make sure I understand what I just did.

I could have used a for or while loop to achieve the same thing and in a sense that’s sort of what recursion is, a loop. I’m calling a method and it’s calling itself over and over again until the condition I put in it is met then it stops. Is that right?

If that’s true, what I don’t understand is where is it holding these new values every time it loops around again? There is no other variable other then the parameter.

I put back ticks, I don’t know why my code isn’t formatted mods.

So every function call adds to the stack in memory and it once it reaches the final function call it returns back down the stack to the bottom, which is the initial call;

I would recommend taking CS50 on EDX.

1 Like
let result = 1, i = 1;
const n = 10;

(function fact(){
  result *= i;
  if (i < n) {
    i++;
    fact();
  }
})();
  
console.log('result:', result);

Every time you call the function, you are adding it to the stack. Imagine each function is a self contained brick which holds its own set of instructions as well as its own memory for variables (oversimplified, I know). If you call the function factorialize() 5 times, then you are adding 5 bricks to the stack. That means that each of those 5 bricks has their own memory with the variable ‘num’. These variables have a scope which keeps them inside of the instance they were called, so the ‘num’ from factorialize().1 is not the same as the ‘num’ from factorialize().2 .

Hope that helps!

The backticks need to be on their own lines, with no whitespace before or after them (which I’ve just now learned). I “fixed” the formatting, but it got rid of all whitespace for some reason. I can only imagine that we’ve upset some coding deity.

Oh well. What’s important is that we tried.

1 Like

That was a perfect explanation I understand now, thank you.