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. The function takes a non-negative integer as an argument and returns the factorial of that number. Factorial of a number ( n ) is the product of all positive integers less than or equal to ( n ), and it is denoted by ( n! ).
Here is the implementation:
function 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: 120Explanation:
- Input Check: The function first checks if the number ( n ) is negative. Factorials are not defined for negative numbers, so an error is thrown if ( n ) is less than zero.
- Iterative Calculation: The function initializes a variable
resultto 1. Then, it uses aforloop to multiplyresultby each integer from 2 up to ( n ). This computes ( n! ) for non-negative integers.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.