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) ...
Get Learning JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.