gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
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 a recursive approach:
javascriptfunction factorial(n) { if (n < 0) { return null; // Factorial is not defined for negative numbers. } if (n === 0 || n === 1) { return 1; // Base case: 0! = 1! = 1 } return n * factorial(n - 1); // Recursive case } // Example usage console.log(factorial(5)); // Output: 120 console.log(factorial(0)); // Output: 1 console.log(factorial(-3)); // Output: nullHere's a breakdown of the function:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.