Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

RECURSION

A recursive function typically is formed when a function calls itself by name, as in the following example:

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

RecursionExample01.htm

This is the classic recursive factorial function. Although this works initially, it’s possible to prevent it from functioning by running the following code immediately after it:

var anotherFactorial = factorial;
factorial = null;
alert(anotherFactorial(4));  //error!

RecursionExample01.htm

Here, the factorial() function is stored in a variable called anotherFactorial. The factorial variable is then set to null, so only one reference to the original function remains. When anotherFactorial() is called, it will cause an error, because it will try to execute factorial(), which is no longer a function. Using arguments.callee can alleviate this problem.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial