Write a function to calculate the factorial of a number (recursive and iterative).
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Iterative Approach:
This approach uses a loop and is often more memory-efficient for large numbers.
function factorialIterative(n) {
if (n < 0) return undefined; // Factorial is not defined for negative numbers
if (n === 0) return 1;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}Recursive Approach:
This approach is more declarative but can lead to stack overflow errors for very large numbers.
function factorialRecursive(n) {
if (n < 0) return undefined; // Base case for invalid input
if (n === 0) return 1; // Base case for recursion
return n * factorialRecursive(n - 1); // Recursive step
}console.log(factorialIterative(5)); // 120
console.log(factorialRecursive(5)); // 120