What a factorial is?
First, let’s define what a factorial is. The factorial of a positive integer n, denoted by n!, is the product of all the positive integers from 1 to n. For example, the factorial of 5 (written as 5!) is equal to 1 * 2 * 3 * 4 * 5, which is 120.
Now that we understand what a factorial is, let’s write a JavaScript function to calculate it. In your code editor, create a new file and name it “factorial.js”. Then, add the following code
Now let’s write JavaScript code to find the factorial of a number:
function factorial(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(5)); // Output: 120
console.log(factorial(4)); // Output: 24
console.log(factorial(3)); // Output: 6
console.log(factorial(2)); // Output: 2
console.log(factorial(1)); // Output: 1
console.log(factorial(0)); // Output: 1
This function, called “factorial”, takes in a single parameter called “n”, which is the number for which we want to find the factorial. The function starts by declaring a variable called “result” and initializing it to 1. This is because the factorial of 0 is defined to be 1
Next, we have a for loop that iterates from 1 to n. On each iteration, the loop multiplies the current value of “result” by the loop counter variable “i”. This has the effect of calculating the factorial of n
Finally, the function returns the result.
Now that we have our factorial function, let’s look at the output of the code below:
Output:
120
24
6
2
1
1
And that’s it! You now have a JavaScript function that can calculate the factorial of any positive integer
- Create a telegram bot step by step using python - June 2, 2023
- Easy way to create a database in MySQL - April 27, 2023
- 5 Unique Hackathon Project Ideas: Creative and Innovative - March 27, 2023