Factorial of Number

Beginner

This tutorial is from open-source community. Access the source code

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:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use recursion to calculate the factorial.
  3. If n is less than or equal to 1, return 1.
  4. Otherwise, return the product of n and the factorial of n - 1.
  5. If n is a negative number, throw a TypeError.

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.