0

Below is a copy/paste from Coderbyte. I'm confused how this works and I'm having trouble finding a suitable answer. Can someone point me in the right direction as to why the child function just automatically inherits the parent function's argument, and is there more going on here than the child function simply not having any arguments and automatically reaching up?

Here is the code.

function FirstFactorial(num) { 

  // our factorial function
  function factorial(n) { 

    // terminate the recursion once we hit zero
    if (n===0) { return 1; }

    // otherwise keep calling the function recursively 
    else { return factorial(n-1) * n; }

  }

  return factorial(num);

}

FirstFactorial(4);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
kevin
  • 2,707
  • 4
  • 26
  • 58
  • 1
    It’s called a “closure” and is common in many other languages that allow lambada functions, nested-functions, or anonymous functions. https://en.m.wikipedia.org/wiki/Closure_(computer_programming) – Dai Oct 21 '18 at 23:42
  • Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Jack Bashford Oct 21 '18 at 23:43
  • 5
    BTW, the actual code you posted does not use a clousure. The inner `factorial` function does not use `num` at all. – Dai Oct 21 '18 at 23:44
  • Your `FirstFactorial` function is completely useless, as the only thing it does is pass the exact same argument to `factorial`. Also you might be interested in [this question](https://stackoverflow.com/questions/1047454/what-is-lexical-scope) if you want to know more about lexical scoping. – Derek 朕會功夫 Oct 21 '18 at 23:45

2 Answers2

3

Not only is the not more going on here…there's less going on than you might think on first glance. Your nested functions are the same as:

function FirstFactorial(num) {
  return factorial(num);
}

function factorial(n) {
  // terminate the recursion once we hit zero
  if (n === 0) { return 1;}
  // otherwise keep calling the function recursively 
  else { return factorial(n - 1) * n;}
}

let f = FirstFactorial(4);
console.log(f)

Which is (for all practical purposes) the same as:

function factorial(n) {
  // terminate the recursion once we hit zero
  if (n === 0) { return 1;}
  // otherwise keep calling the function recursively 
  else {return factorial(n - 1) * n;}
}

let f = factorial(4);
console.log(f)

The outer function is just wrapping the inner function and calling it…for no apparent reason.

Mark
  • 90,562
  • 7
  • 108
  • 148
1

It's not inheriting the argument - if you look at this line:

return factorial(num);

Then you see that the inner function (factorial) is being called with the parameter of the parent function - no inheritance happening here, just a call.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79