a
and b
represent the current number of the sequence and the next number of the sequence, starting from 0
and 1
. n
is a count-down timer that specifies which element of the fibonacci sequence will be returned (EG: n = 10
will return 55
).
This function works by accepting an argument n
which means it will calculate nth number of the sequence:
function fib(n) {
The code then defines a function that will calculate the next number in the sequence:
function(n,a,b) {
return n>0 ? arguments.callee(n-1,b,a+b) : a;
}
Basically this anonymous function counts down n
by one each time it is executing, while at the same time moving a
and b
to the next numbers in the sequence. If n
is equal to 0
then the sequence is complete and the current number a
is returned.
arguments.callee refers to the currently executing function, so that code just means to call back into itself with the new arguments. In other words, to begin the next iteration of the "loop".
Finally, by saying (n,0,1);
the code is actually calling into fib
with the parameters n,0,1
. The return
statement - which I left out of the above snippet - takes the return value of the anonymous function and returns it to the caller of fib
.
That said, using recursion in this manner is inefficient for languages such as JavaScript that do not have tail call optimization. For large n
you would be better off writing this using a standard looping construct instead of recursion.