Eloquent JavaScript: Can't understand recursion example -
this question has answer here:
from page 50 of haverbeke's second edition. added couple of console.log try better track progress.
function power(base, exponent) { if (exponent == 0) { console.log("line 5 " + base + " " + exponent); return 1; } else console.log("line 10 " + base + " " + exponent); return base * power(base, exponent -1); } console.log(power(2,3));
// output
line 10 2 3 line 10 2 2 line 10 2 1 line 5 2 0 8
//
i expect final output 1
since when if (exponent == 0)
true, next statement return 1;
, appears enter else
1 more time return 8. shouldn't return
kick out of function.
obviously newbie or wouldn't stuck on page 50 of supposedly beginner book.
thanks help.
whenever function enters "else" branch, new stack frame created, waiting result of recursive call. can imagine evaluation step step:
power(2, 3)
enterselse
branch, , returnsbase * power(base, exponent - 1)
.2 * power (2, 2)
enterselse
branch, , returnsbase * power(base, exponent - 1)
.2 * (2 * power (2, 1))
enterselse
branch, , returnsbase * power(base, exponent - 1)
.2 * (2 * (2 * power (2, 0)))
entersif
branch, , returns1
.you can evaluate result:
2 * (2 * (2 * 1))
,8
.
Comments
Post a Comment