Calculating Factorial in JavaScript | JavaScript Tutorial #shorts #javascript #js

Posted by

Factorial in JavaScript

Factorial in JavaScript

In JavaScript, you can calculate the factorial of a number using a simple recursive function. The factorial of a number is the product of all positive integers up to that number.

Here’s how you can write a factorial function in JavaScript:


function factorial(num) {
    if (num === 0) {
        return 1;
    } else {
        return num * factorial(num - 1);
    }
}

// Calculate the factorial of 5
var result = factorial(5);

console.log(result); // Output: 120

In the above code, we define a function called factorial that takes a number as an argument. If the number is 0, we return 1 as the factorial of 0 is always 1. Otherwise, we recursively call the factorial function with num – 1 until we reach the base case of 0.

Now, let’s create a simple HTML page to demonstrate the factorial function in action:





    
    
    Factorial in JavaScript
    



Factorial in JavaScript

The factorial of 5 is .

var result = factorial(5); document.getElementById('result').innerText = result;

In the above HTML code, we include the factorial function defined in a separate JavaScript file called “factorial.js”. We then calculate the factorial of 5 and display the result on the page using the script tag.

And there you have it! You now know how to calculate the factorial of a number in JavaScript using a recursive function. Happy coding!