Write a function in Nodx.js that calculates the factorial of a number.
- User
Write a function in Nodx.js that calculates the factorial of a number.
- Assistant
It seems there is a slight typographical error in your request. You likely meant "Node.js" instead of "Nodx.js". Below is a simple function to calculate the factorial of a number in Node.js using JavaScript:
javascriptfunction factorial(n) { if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } if (n === 0 || n === 1) { return 1; } return n * factorial(n - 1); } // Example usage: console.log(factorial(5)); // Output: 120Here's what the function does:
-
Error Handling for Negative Numbers: The factorial function is not defined for negative numbers. So, if
nis negative, the function throws an error. -
Base Case: The factorial of or is . This is the base case for the recursive function.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.