Functions and Recursion
Tip
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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access