11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Note that this isn‘t a terribly robust function—if you pass it strings or other data types that<br />

shouldn‘t be added, it will try to sum those as well. We‘ll see more sophisticated uses of<br />

functions taking a variable number of parameters when we present various <strong>JavaScript</strong><br />

applications later in the book. We will also see functions used as objects starting in the next<br />

chapter. For now, let‘s turn our attention to a special technique used in creating functions—<br />

recursion.<br />

Recursive Functions<br />

A recursive function is one that calls itself. While not always the most efficient execution (timewise)<br />

way to perform a computation, the elegance of a recursive function is very appealing.<br />

Many programmers find the simplicity with which some computation can be expressed in a<br />

recursive fashion to outweigh the disadvantage of the overhead incurred by repeated function<br />

invocation.<br />

Consider the definition of factorial from mathematics, where given a number n,<br />

n! = n* (n–1) * (n–2) * … * 1<br />

So, given this definition of factorial, 5! = 5 * 4 * 3 * 2 * 1, or 120. For completeness, 0! is defined<br />

to be 1, and factorial of negative numbers is not defined. We could write a recursive function to<br />

calculate the factorial in a somewhat naïve fashion. Here, the function factorial keeps calling<br />

itself with smaller and smaller values until the base case of 0 is hit, at which point the results<br />

are returned ―upward‖ until the calculation is complete.<br />

function factorial(n)<br />

{<br />

}<br />

if (n == 0)<br />

else<br />

return 1;<br />

return n * factorial(n-1);<br />

Passing the function a positive value, we see that<br />

alert(factorial(5));<br />

produces the desired result:<br />

However, if a negative value is passed to the function, the recursion will continue indefinitely.<br />

Notice the error produced by Internet Explorer in such a case:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!