+ 2

Someone please explain to me why the next code give 4. I dont understand at all. Shouldn't be 2?

function f(x) {if (x==4) return 4; else return f(x+1)}; alert (f(1)); Cause in my undestanding if x equal 4 the result is 4. (X could be anything resultin 4). So in alert f(1) x is not 1? Different from 4. So we not go on "else" path? I found this in one javascript chalenge. I also verified in Playground and the result is 4 indeed but I dont understand why. Thank you.

26th Feb 2018, 7:07 AM
Sunny
Sunny - avatar
3 ответов
+ 5
It is because the else statement don't return x+1 but f(x+1). So it's returning f(2),then f(3),then f(4) which returns 4.
26th Feb 2018, 7:14 AM
Αητοιπe
Αητοιπe - avatar
+ 4
Yes, it's a recursive function that keeps calling f (x+1) till x+1 == 4 . f (5) would recurse infinitely.
26th Feb 2018, 8:39 AM
Eric Blinkidu
Eric Blinkidu - avatar
0
Thank you very much. Now is clear. God, I'm rusty! Cause now I remember the recursive functions, but it didn't cross my mind then. Great to be in such fast helping community. Thank you, Antoine and Eric.
27th Feb 2018, 6:18 AM
Sunny
Sunny - avatar