JavaScript: Find the Factorial of a Number

1. Introduction

The factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 5 is 1*2*3*4*5 = 120. Factorial is not defined for negative numbers, and the factorial of zero is one, 0! = 1. In this guide, we'll create a simple JavaScript program to compute the factorial of a given number.

2. Program Overview

During this tutorial, we will:

1. Declare a number whose factorial we wish to compute.

2. Develop a function to calculate the factorial.

3. Showcase the result.

3. Code Program

let num = 5;  // Number for which factorial is to be computed
let factorial = 1;  // Resultant variable to store the factorial

// Function to compute factorial
function computeFactorial(n) {
    if (n === 0 || n === 1) {
        return 1;  // The factorial of 0 or 1 is 1
    }
    for (let i = 2; i <= n; i++) {
        factorial *= i;  // Multiply factorial with each number from 2 to n
    }
    return factorial;
}

factorial = computeFactorial(num);

console.log("The factorial of " + num + " is: " + factorial + ".");

Output:

The factorial of 5 is: 120.

4. Step By Step Explanation

1. Variable Initialization: We start by defining the variable num, representing the number for which we aim to find the factorial. We also declare a variable factorial initialized to 1, which will store our result.

2. Factorial Function: The computeFactorial(n) function is designed to determine the factorial of a number.

- If \( n \) is 0 or 1, the function instantly returns 1, as their factorial is 1.- The loop runs from 2 to \( n \), multiplying the factorial with each consecutive number.

3. Assigning the Result: We then call our function with the given number, and the outcome is stored in the factorial variable.

4. Displaying the Result: Using the console.log function, we present the factorial of the number in a concise and clear manner.

Comments