Home > other >  Where is the result of each function call stored in this factorial method?
Where is the result of each function call stored in this factorial method?

Time:02-22

Here is an object with a method that will return the factorial of a number via recursion. What I can't wrap my head around is where the value of the factorialized variable is being stored when the function calls itself again and multiplies inputNumber by itself -1. Could someone explain this to me?

const Calculate = {
  factorial(inputNumber) {
    if (inputNumber < 2) { return 1 };
    const factorialized = inputNumber * this.factorial(inputNumber - 1);
    
    return factorialized;
    }
  }

Calculate.factorial(5);


CodePudding user response:

Many language has Memory Heap to save value for their operations, etc.

Image your function will execute 3 times:

  • the the result from 1th execution will be allocate to [k] position of Memory Heap
  • then the 2th execution will allocate to [k 1] position
  • the 3th execution will allocate to [k 2] position and will be calculate the value and save into [k 2] position
  • then the 2th function will use the [k 2] position to calculate their result
  • then the 1th function will use the [k 1] position to calculate their result
  • finally will return the value

Some addtion information

  • Related