a and b represent the current sequence number and the next sequence number, starting at 0 and 1 . n is a countdown timer that indicates which element of the fibonacci sequence will be returned (EG: n = 10 will return 55 ).
This function works by taking the argument n , which means that it will calculate the nth sequence number:
function fib(n) {
The code then defines a function that will calculate the following number in the sequence:
function(n,a,b) { return n>0 ? arguments.callee(n-1,b,a+b) : a; }
Basically, this anonymous function counts n for each time it is executed, while at the same time moving a and b to the next numbers in the sequence. If n is 0 , then the sequence ends and the current number a returned.
arguments.callee refers to the current executable function, so the code simply means to call new arguments into itself. In other words, to start the next iteration of the "loop".
Finally, saying (n,0,1); , the code really calls the parameters n,0,1 in fib . The return , which I missed from the above snippet, takes the return value of the anonymous function and returns it to the caller fib .
However, using recursion in this way is inefficient for languages like JavaScript that do not have tail call optimization. For large n you'd better write this using a standard loop construct instead of recursion.
Justin ethier
source share