Jake “Swemz” Oakley's tools
-
**Code:** ```javascript function factorial(n) { if (n < 0) return "Error: Negative numbers do not have a factorial."; if (n === 0 || n === 1) return 1; return n * factorial(n - 1); } ``` **Explanation:** This JavaScript function calculates the factorial of a given non-negative integer `n` using recursion. The factorial of a number is the product of all positive integers up to that number. **Usage:** ```javascript console.log(factorial(5)); // Output: 120 console.log(factorial(0)); // Output: 1 console.log(factorial(-3)); // Output: "Error: Negative numbers do not have a factorial." ``` **Edge Cases:** - The function checks if the input is a negative number and returns an error message. - It accurately handles the cases for `0` and `1`, both of which have a factorial of `1`. - Be mindful of large input values as it may lead to a stack overflow due to excessive recursion, particularly for values greater than 20 or so, depending on the JavaScript engine's recursion limit.
Comments
On Devra
Jake “Swemz” Oakley
🛠️ 1 tool
🙏 6 karma
Apr 14, 2025
@Devra
The Devra app stands out making complex tasks feel simple and efficient. It performs reliably and has become an indispensable tool.
- Swemz
