Skip to content

Instantly share code, notes, and snippets.

@ddeveloperr
Last active August 29, 2015 14:18
Show Gist options
  • Save ddeveloperr/37ff6a1073971642ed3f to your computer and use it in GitHub Desktop.
Save ddeveloperr/37ff6a1073971642ed3f to your computer and use it in GitHub Desktop.
Recursion in JS examples
/*Recursion
It is perfectly okay for a function to call itself, as long as it takes care not to overflow the stack. A function that calls itself is called recursive. Recursion allows some functions to be written in a different style. */
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
console.log(power(2, 3));
// → 8
// Example : Computing the factorial of a number using a recursive function
function factorial(n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
factorial(5);
// Output : 120
// Example from codeacademy.com
function makeRobots(robotsNeeded){
// Do we need any robots?
if(robotsNeeded>0){
// We do? Well lets make one
console.log("Robot "+ robotsNeeded+" Created");
// Removes 1 from robots Needed
// Also the same as saying robotsNeeded = robotsNeeded -1
robotsNeeded--;
// Calls makeRobots with the new number of robots needed
makeRobots(robotsNeeded);
}
}
makeRobots(5);
// More details: https://developer.mozilla.org/en-US/docs/Glossary/Recursion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment