Recursive Factorial
Predict Output Medium
Question
What does this code print?
Code
function fact(n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
console.log(fact(4));
Hint
4! = 4 * 3 * 2 * 1.
Explanation
fact(4) = 4 * fact(3) = 4 * 3 * fact(2) = 4 * 3 * 2 * fact(1) = 4 * 3 * 2 * 1 = 24. The base case fact(1) returns 1, stopping the recursion. The output is: 24
Related Resources
Related Lessons
- Recursion
Learn recursion.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.