Eloquent JavaScript Recursion Return? -
i having hard time understanding recursion in eloquent javascript, easy know happening cannot understand why..
function power(base, exponent) { if (exponent == 0) return 1; else return base * power(base, exponent - 1); /* 2*2*2, returns base? thought @ first was, 2*(2,3-1) return 2*(2,2)? calling until reach 0, why exponent out?*/ } console.log(power(2, 3)); // → 8
recursive functions can expressed loop. see adaptation:
function power(base, exponent) { var result = 1; (var = 0; < exponent; i++) result *= base; return result; }
as can see, exponent doesn't play role @ in output, represents number of loops make.
in world of recursion, exponent represents number of times function has yet call before can return.
this youtube video visualizes recursion nicely: computerphile
Comments
Post a Comment