Search code examples
javascriptcallfunc

javascript explain this code function call it self


please someone explain this to me

function func(x, n) {
  if (n == 1) {
    return x;
  } else {
    return x * func(x, n - 1);
  }
}
console.log(func(2, 4)); // 16

how do answer is 16

I could not understand more than this when if is false it going to else in the return section function call itself at the first input is the same value as x, ie 2 at the second input is n - 1 when function run again the value of x remains the same as 2 and the value of n becomes 3 that's mean 3 times if is false in the 4 times if if true and the execution loop ends and show answer in alert i can not figure out what number is multiplied by x per run or the answer should be the same as 2 because every time the function is executed, shouldn't the value of x be equal to 2?


Solution

  • If you are asking about how recursion works, then I will explain you with this basic flowchart diagram. enter image description here

    I also edited your JS Code so it will provide you with clarification.

    function func(x, n) {
      if (n == 1) {
        return x;
      } else {
        let function_returned = func(x, n - 1);
        console.log(x, "*", function_returned, "=", x*function_returned)
        return x * function_returned
      }
    }
    console.log(func(2, 4));