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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -