Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

Write a function in JavaScript that calculates the factorial of a number.

  1. User

    Write a function in JavaScript that calculates the factorial of a number.

  2. Assistant

    Certainly! Here's a JavaScript function that calculates the factorial of a number using an iterative approach:

    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: 120
    

    Here's a breakdown of the function:

    • The function factorial takes an integer n as an argument.
    • It throws an error if n is negative, as factorials are not defined for negative numbers.
    • It initializes a variable result to 1, as the factorial of 0 is 1 (0! = 1) and it's the multiplicative identity.
    • A for loop is used to multiply result by each integer from 2 up to n.
    • Finally, it returns the computed result.

    If you prefer a recursive approach, you can also define the function like this:

    function factorial(n) {
        if (n < 0) {
            throw new Error("Factorial is not defined for negative numbers.");
        }
        if (n === 0 || n === 1) {
            return 1;
        }
        return n * factorial(n - 1);
    }
    
    // Example usage:
    console.log(factorial(5)); // Output: 120
    

    In the recursive version, the function calls itself with n - 1 until it reaches the base case n === 0 or n === 1, at which point it returns 1.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.