Recursive functions in JavaScript
If you have learned other programming languages, you should know the recursion problem. recursive functions are formed when a function calls itself by name.
function fac(num){if(num<=1){return 1;}else{return num*fac(num-1);}}
This is a classic factorial algorithm, which implements what we call recursion. This Code seems to have no problem. It is described in c or other programming languages, but sometimes errors occur in JavaScript. For example:
Var myfac = fac; fac = null; console. log (myfac (4); // Error
Why?
Fac references the original function to myfac and sets the fac to null. The reference to the original function is still in myfac. It should be accessible! This problem occurs. When calling myfac, fac () is no longer a function, and thus an error occurs, in this case, use arguments. callee (pointing to the function being executed) can solve this problem.
function fac(num){if(num<=1){return 1;}else{return num*arguments.callee(num-1);}}
Use arguments. instead of the function name, callee ensures that no problem exists when calling a function. Therefore, when writing a recursive function, arguments is used. calllee () is much safer than using a function name.
However, in strict mode, arguments. callee cannot be accessed through scripts. Access to this attribute may lead to errors, but the same effect can be achieved by using a name function expression.
var fac=(function f(num){if(num<=1){return 1;}else{return num*f(num-1)}});