O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Recursive Functions

A recursive function is a function that calls itself. The following code shows a simple example of recursion. Every time trouble( ) runs, it calls itself again:

function trouble () {
  trouble();
}

A recursive function that calls itself unconditionally, as trouble( ) does, causes infinite recursion (i.e., a state in which a function never stops calling itself). If left unchecked, infinite recursion would theoretically trap a program in an endless cycle of function execution. To prevent this from happening, practical recursive functions call themselves only while a given condition is met. One classic use of recursion is to calculate the mathematical factorial of a number, which is the product of all positive integers less than or equal to the number. For example, the factorial of 3 (written as 3! in mathematical nomenclature) is 3 * 2 * 1, which is 6. The factorial of 5 is 5 * 4 * 3 * 2 * 1, which is 120. Example 5-1 shows a factorial function that uses recursion.

Example 5-1. Calculating factorials using recursion

function factorial (n) {
  if (n < 0) {
    return;  // Invalid input, so quit
  } else if (n <= 1) {
    return 1;
  } else {
    return n * factorial(n-1);
  }
}

// Usage:
factorial(3);  // Returns: 6
factorial(5);  // Returns: 120

As usual, there is more than one way to skin a proverbial cat. Using a loop, we can also calculate a factorial without recursion, as shown in Example 5-2.

Example 5-2. Calculating factorials without recursion

function factorial (n) { if (n < 0) { return; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required