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
To calculate the factorial of a number in JavaScript, you can use either an iterative approach or a recursive approach. Here's how to implement both:
Iterative Approach
The iterative approach uses a loop to calculate the factorial.
javascriptfunction factorialIterative(n) { if (n < 0) return undefined; // Factorial is not defined for negative numbers let result = 1; for (let i = 2; i <= n; i++) { result *= i; } return result; }Recursive Approach
The recursive approach involves the function calling itself to solve smaller instances of the problem until the base case is reached.
javascript
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.