Reputation: 233
I am new to JavaScript. Recently I was asked what the result of the following code is. I'm not totally sure how to answer this question. Can anyone provide what they think the answer is?
(function f(x, y, m) {
if (m > 0) { return f( y, x + y, m - 1 ); }
return y;
}(1, 2, 7) );
Upvotes: 0
Views: 228
Reputation: 4679
result
55
Why, first because I launched in the console. This a recursion, teh stop condicion is the m, that if look always is reduced by 1. This mind that he call it 8 times, the last one return direcly the second param.
This mind that the only important here is the second param, that is call by x + y
and Y moving to the first param.
(((((((1 + 2 ) + 2 ) + 3 ) + 5) + 8 ) + 13 ) + 21)
That is a fibonacci sequence starting in 1 and 2 :) This function provide the position m + 2 (you provide the 2 first numbers) in the fibonacci sequence starting in x and y
1, 2, 3, 5, 8, 13, 21, 34, 55
http://en.wikipedia.org/wiki/Fibonacci_number
Upvotes: 2