Write a function in JavaScript that calculates the factorial of a number.
- User
Write a function in JavaScript that calculates the factorial of a number.
- Assistant
Certainly! Here's a JavaScript function that calculates the factorial of a number using a recursive approach:
javascriptfunction factorial(n) { if (n < 0) { return undefined; // Factorial is not defined for negative numbers } if (n === 0 || n === 1) { return 1; // Base case: factorial of 0 and 1 is 1 } return n * factorial(n - 1); // Recursive case } // Example usage: console.log(factorial(5)); // Output: 120 console.log(factorial(0)); // Output: 1 console.log(factorial(1)); // Output: 1 console.log(factorial(10)); // Output: 3628800
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.