javascript - What is the logic behind this double function call with recursion? -
where have console logs, countdown seems count down 10 1 (this makes sense) after this, way seems add 15 final result of countdown 9 times, happen, i'd imagine after each countdown loop, way called, each keeps track of own value? clarification why , when of logic helpful - thanks!
var countdown = function(value) { value = value - 1; if (value == 0) { return value; } console.log("loop 1 " + value); return way(countdown(value)); }; function way(value) { value = value + 15; console.log(value); return value; } countdown(10);
as commented above value local variable in either function , bound scope of either function. doesn't contribute confusion aside expecting complexity there. ;)
the behaviour arises countdown() being called recursively , calling way() has wait until recursive calls countdown() returning. that's not happening until countdown()'s recursion has stopped @ value 0 returned eventually. after countdown() isn't invoked ever again, since countdown() invoked recursively , bubbling through invocations of countdown() there multiple calls way() result returned countdown() called @ end in turn calling way() result of countdown() etc. ... ok, got bit confused here myself.
since value isn't required complex might eliminate reducing code:
function countdown(value) { if ( value == 1 ) { return 0; } // bail out condition console.log("loop 1 " + value) return way( countdown( value - 1 ) ); }; function way( value ) { console.log(value); return value + 15; } countdown(10); way() of no relevance recursion , might substituted:
function countdown(value) { if ( value == 1 ) { return 0; } // bail out condition console.log("loop 1 " + value) return countdown( value - 1 ) + 15; }; countdown(10); due recursion code diving stack 9 frames deep. , bubbling stack returning result of every passed frame increased 15 prior bubbling further on.
so actually, there 1 recursion.
Comments
Post a Comment