Recursive functions in JavaScript

Source: Internet
Author: User

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)}});
 

 



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.