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 simple JavaScript function that calculates the factorial of a given non-negative integer using an iterative approach:
javascriptfunction factorial(n) { if (n < 0) { throw new Error("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(factorial(5)); // Output: 120 console.log(factorial(0)); // Output: 1This function computes the factorial iteratively by initializing a result variable to 1 and then multiplying it by each integer up to the number
n. The calculation handles the edge case of0!, which is defined to be 1. If a negative number is passed as an argument, the function throws an error since factorials are not defined for negative numbers.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.