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 both an iterative and a recursive approach. You can choose the method you prefer.
Iterative Approach:
javascriptfunction factorialIterative(n) { if (n < 0) { return 'Factorial is not defined for negative numbers'; } let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; } // Example usage: console.log(factorialIterative(5)); // Output: 120Recursive Approach:
javascript
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.