HTML and CSS Reference
In-Depth Information
Figure 7.14 The closure remembers the values of local variables.
7.1.5 Recursion
Definition of recursion:
recursion: See recursion.
This definition says it all! JavaScript sup-
ports recursion. So what is it? Have you
ever taken apart a Russian doll? Open up
the outside doll and there's another
smaller duplicate doll inside it, take that
one out, and you find another, and so on, until you get down to a tiny doll at the end.
Then when you put them back, you start with the last doll you opened and keep return-
ing each doll until you get back to the first one you opened. A recursive function is a
function that calls itself. It's a chain of function calls to the same function. The first time
it calls itself is the first level of recursion, the second time is the second level, and so on.
When a function calls itself, execution starts at the beginning of the function, and when
the function ends, the program backs up to where it was when it called the function and
starts executing from that point. Most important, there must be a way to stop the recur-
sion, or it will be infinite, and probably cause the program to crash.
An example often used to describe recursion can be demonstrated with a function to
produce a Fibonacci sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, and so on.
Here is a little bit of history about how this formula was derived.
In the beginning of the 13th century, an Italian mathematician, Leonardo Fibonacci,
was trying to solve the following problem presented at a mathematical competition in
Pisa: How many rabbits would be produced in a year if, beginning with a single pair of
rabbits, every month each pair reproduces a new pair of rabbits, which become produc-
tive when they are one month old, and none of them die, and so on? Fibonacci came up
 
 
Search WWH ::




Custom Search