Section 5.3. Functions and Recursion


5.3. Functions and Recursion

Recursion is not a commonly occurring functionality in most JavaScript applications. It's also a fairly advanced form of programming. As such, you may want to skip this section for now and return to it after you've finished the rest of the book.


A function that calls itself is known as a recursive function. Typically, it's used when a process must be performed more than once, with each new iteration of the process performed on the previously processed result. The use of recursion isn't common in JavaScript, but it can be useful when dealing with data that's in a tree-line structure, such as the Document Object Model. However, it can also be memory- and resource-intensive, as well as complicated to implement and maintain. As such, use recursion sparingly.

Previously in the chapter I wrote about named function literals, in which the function is given a name but only the function itself can access that name. This is an ideal setup for recursion.

In Example 5-5, a recursive function is used to traverse a numeric array, add the numbers in the array, and add the numbers to a string.

Example 5-5. JavaScript function recursion

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Recursion</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <script type="text/javascript"> //<![CDATA[ var addNumbers = function sumNumbers(numArray,indexVal,resultArray) {        // recursion test    if (indexVal == numArray.length)        return resultArray;    // perform numeric addition    resultArray[0] += Number(numArray[indexVal]);    // perform string addition    if (resultArray[1].length > 0)       resultArray[1] += " and ";    resultArray[1] += numArray[indexVal].toString(  );        // increment index    indexVal++;    // call function again, return results    return sumNumbers(numArray,indexVal,resultArray); } // create numeric array, and the result array var numArray = ['1','35.4','-14','44','0.5']; var resultArray = new Array(0,''); // necessary for the initial case // call function var result = addNumbers(numArray,0, resultArray); // output document.writeln(result[0] + "<br />"); document.writeln(result[1]); //]]> </script> </body> </html>

In this application, the function calls itself using its internal name repeatedly until the array index is equivalent to the length of the numeric array. The result is then returned and passed up via each recursive call until it's returned to the statement that first invokes the function. Think of each iteration of the function call as pushing the string and numeric sum onto a stack, and when the numeric array has been traversed, the string and number have to be popped up through the stack to the top.

Of course, with this example, a while loop could be used to create the same results. However, as I mentioned earlier, when we're working with tree-structured data such as the DOM, recursion is extremely valuable, as is the function literal used to implement this process. However, not all uses of function literals in all browsers are without potential negative side effects. One area of risk is with nested functions, and possible memory leaks from an item called closure.




Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net