I was just experimenting with some recursion and noticed something that confused me. Let me illustrate with some code examples:
function loop(x) {
if (x >=
The order in which this recursive call will evaluate will be from the last call down. The function that gets evaluated first is the loop(10) which returns a value of 10. The next will be loop(9) and so on. Think about what loop(9) will look like when it is called:
loop(9) {
if (x >= 10)
return x;
10
}
loop(9) will return undefined. loop(8) will as well... and so on.
Conversely, if you return the value of the recursive call it would look like this:
loop(9) {
if (x >= 10)
return x;
return 10
}
and by the time your initial function call gets executed it will look like this:
loop(0) {
if (x >= 10)
return x;
return 10
}
I created a jsfiddle to demonstrated the point: http://jsfiddle.net/TSnxp/