function Expression-recursive

Source: Internet
Author: User

Recursive

A recursive function is formed when a function is called by itself.

1     function factorial (num) {2         if (num <=1) {3             return 1; 4         Else {5             return num * factorial (num-1); 6         }7     }

This is a classic recursive factorial function, but the following code will make it error

1     var anotherfactorial = factorial; 2     NULL ; 3     Console.log (Anotherfactorial (4)); // factorial is not a function

When executing the anotherfactorial () function, factorial is no longer a function.

Arguments.callee is a pointer to a function that is executing, so why use it to implement recursive calls to functions

1     function factorial (num) {2         if (num <=1) {3             return 1; 4         Else {5             return num * Arguments.callee (num-1); 6         }7     }

However, in strict mode, Arguments.callee cannot be accessed through a script, and accessing this property can result in an error. However, you can use a named function expression to achieve the same result

1     varFactorial = (functionf (num) {2         if(Num <= 1){3             return1;4}Else {5             returnnum * F (num-1);6         }7     });8 9     varAnotherfactorial =factorial;Tenfactorial =NULL; OneConsole.log (Anotherfactorial (4));// -

function Expression-recursive

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.