Skip to content

Instantly share code, notes, and snippets.

@gojun077
Created September 21, 2012 13:20
Show Gist options
  • Save gojun077/3761419 to your computer and use it in GitHub Desktop.
Save gojun077/3761419 to your computer and use it in GitHub Desktop.
CodeAcademy - Recursion in Javascript Sec 2/5, Ex 5/5
/*
Now that we've covered the bare essentials, try rebuilding the
factorial() function we've been working on, but this time write
it all from scratch. To help you along, here are five questions
that you can use whenever using recursion in your code:
-What is/are the base case(s)?
-What is/are the recursive case(s)?
-Have I included any other necessary termination condition(s)?
-Do the statements in the function lead to the base case?
-Does the recursion build on the base case until the desired
result is returned by the function?
Define the base case. Since a factorial is multiplying an
integer by each integer between it and one, the base case is one.
Define the recursive case. What action needs to be performed
over and over again in order to achieve the desired result?
Write any termination conditions to prevent the function from
accepting arguments that would trigger an error.
*/
function factorial(n) {
//termination condition
if (n<0) {
console.log("Only non-negative numbers allowed");
return;
}
//base case
if (n===1) {
return 1;
}
//recursion
return n * factorial(n-1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment