1. Base case
The smallest input answered directly, with no further calls.
if (n <= 1)Typorithm · easy
Step 1 of 8 · intro card
Basic Patterns
Recursion solves a problem by combining the answer to a smaller version of itself.
Every recursive function needs a base case that returns without recursing.
The recursive step must shrink the input toward that base case.
Each call waits on the stack until the smaller call returns its answer.
Base case first, always.
Shrink the input every call.
Trust the smaller call's answer.
function factorial(n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}Connect each part of the code to the concept before you type.
The smallest input answered directly, with no further calls.
if (n <= 1)factorial(1) and factorial(0) are both 1 by definition.
return 1Combine the current value with the answer for a smaller input.
return n * factorial(n - 1)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.