5.3. Functions and Recursion
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
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. |