Introduction
In this lab, we will be learning how to calculate the factorial of a number using recursion in JavaScript. We will also learn how to throw a TypeError if the input is a negative number. By the end of this lab, you will have a better understanding of recursion and how it can be used to solve mathematical problems.
Calculating the Factorial of a Number
To calculate the factorial of a number, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use recursion to calculate the factorial.
- If
nis less than or equal to1, return1. - Otherwise, return the product of
nand the factorial ofn - 1. - If
nis a negative number, throw aTypeError.
Here is the code to calculate the factorial:
const factorial = (n) =>
n < 0
? (() => {
throw new TypeError("Negative numbers are not allowed!");
})()
: n <= 1
? 1
: n * factorial(n - 1);
You can test the code by calling the factorial function with a number as an argument:
factorial(6); // 720
Summary
Congratulations! You have completed the Factorial of Number lab. You can practice more labs in LabEx to improve your skills.