Factorial Code works but why

Deadly 提交于 2019-12-02 12:59:20

What you have here is a recursive function - a function which calls itself. You also need to keep in mind the "scope" of the variables in the function.

The scope of the parameter "n" is local to the function. Every time the function is called, the new variable is created. The scope of each variable is the function execution.

1: function factorial(n) {
2:     if (n === 0) {
3:         return 1;
4:     }
5:     console.log(n);
6:     return n * factorial(n - 1);
7: }

Example:

Parameter Value = 0
Hence, n = 0
Execute factorial(0)
1. line 1: variable n = 0
2. line 2: check if n = 0
3. line 3: return 1

Example:

Parameter Value = 2
Hence, n = 2
Execute factorial(2)
1. line 1: variable n = 2 (scope = execution #A)
2. line 5: console log n = 2
3. line 6: return 2 * factorial(2-1) // Function calls itself
    4. line 1: variable n = 1 (scope = execution #B)
    5. line 5: console log n = 1
    6. line 6: return 1 * factorial(1-1) // Function calls itself
        7. line 1: variable n = 0 (scope = execution #C)
        8. line 3: return 1 // #C returns 1
    9. return 1 * 1 // #B returns 1 * 1 (from #C)
10. return 2 * 1 // #A returns 2 * 1 (from #B)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!