I do not see how this recursive function works:
function f(n) { g(n-1) }
function g(n) {
alert("before: " + n);
if(n > 0) f(n);
alert("after: " + n);
}
f(2);
I have tried to understand this code works and I saw how “before 1”, “before 0”, and “after 0” execute but… how does “after 1” come from this?
I see it executing as this… f(2) calls g which subtracts 1 so ‘n’ becomes 1. Alert(“before: ” + n) is executed, 1 is greater than 0 so it will recall itself and subtract 1. Alert(“before:” + n) is executed once again, 0 is not greater than 0 so it will execute Alert(“after:” + n) and the function ends?…
Edit: Thank @FlorianMargaine and @Cyrille for helping me understand the logic behind this. =)
after 1comes from the fact that in Javascript, parameters are passed by value instead of by reference. So on the first iteration, callingif(n > 0) f(n);which callsg(n-1)does NOT decrementn. Its value is kept for whenif(n > 0) f(n)returns, and remains at its value of 1.Here’s a call graph: