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! A factorial of a number ( n ) is the product of all positive integers less than or equal to ( n ). The factorial is denoted as ( n! ). Here is a JavaScript function that calculates the factorial of a given number using a recursive approach:
javascriptfunction factorial(n) { // Check for valid input if (n < 0) { throw new Error('Factorial is not defined for negative numbers'); } // Base case: 0! is 1 if (n === 0) { return 1; } // Recursive case return n * factorial(n - 1); } // Example usage: console.log(factorial(5)); // Output: 120Alternatively, you can also implement the factorial function using an iterative approach, which is often more efficient in JavaScript because it avoids the potential pitfalls of deep recursion:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.