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! Below is a JavaScript function that calculates the factorial of a number using a recursive approach. The factorial of a non-negative integer ( n ) is the product of all positive integers less than or equal to ( n ). It is denoted as ( n! ).
javascriptfunction factorial(n) { // Base case: if n is 0 or 1, the factorial is 1 if (n === 0 || n === 1) { return 1; } // Recursive case: n! = n * (n-1)! return n * factorial(n - 1); } // Example usage console.log(factorial(5)); // Output: 120Explanation:
- The function takes a single argument .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.