Predict Factorial Output
Predict Output Medium
Question
What does this code print?
Code
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(4));
Hint
factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = ...
Explanation
factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * factorial(1) = 4 * 3 * 2 * 1 = 24. The base case (n <= 1) returns 1, stopping the recursion. The chain unwinds: 1 → 2 → 6 → 24.
Related Resources
Related Lessons
- Recursion
Learn about recursive functions.
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.