Recursive functions in JS

Source: Internet
Author: User
In programming languages, the function Func (Typea ,......) Call the function itself directly or indirectly. This function is called a recursive function. Recursive functions cannot be defined as inline functions. This article mainly introduces information about recursive functions in JS. For more information, see Func (Type a,…) in the programming language ,......) Call the function itself directly or indirectly. This function is called a recursive function. Recursive functions cannot be defined as inline functions.

Recursive functions:

function factorical(num){  if(num<=1){    return 1;  }  else{    return num*factorical(num-1);  }}factorial(2)//2

This recursive function uses a function to call the function itself. But is this really good? Let's take a look at it.

Var another = factorical; factorical = null; console. log (another (2) // an error is reported that factorical not a function

This is the drawback of function calling. How can this problem be solved?

function factorical(num){  if(num<=1){    return 1;  }  else{    return num*arguments.callee(num-1);  }}var another=factorical;factorical=null;console.log(another(2))//2

If you use arguments. callee to replace the function name, you can ensure that the function will not go wrong no matter how it is called.

The above is the recursive function in JS introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in time. I would like to thank you for your support for PHP chinnet!

For more articles about recursive functions in JS, please follow the PHP Chinese website!

Related Article

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.