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! You can create a function to calculate the factorial of a number in JavaScript using either an iterative or recursive approach. Below, I'll provide both implementations for clarity.
Iterative Approach
function 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; } // Example usage: console.log(factorialIterative(5)); // Output: 120Recursive Approach
function factorialRecursive(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 or 1 is 1 } return n * factorialRecursive(n - 1); } // Example usage: console.log(factorialRecursive(5)); // Output: 120Both functions compute the factorial of a given number
n. The iterative method uses a loop, making it easy to understand and less memory-intensive for large values ofn. The recursive method, on the other hand, is more elegant but can lead to stack overflow errors if is too large due to deep recursion. Choose the implementation based on your needs and constraints.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.