Factorial of Number

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/error_handle("`Error Handling`") subgraph Lab Skills javascript/variables -.-> lab-28293{{"`Factorial of Number`"}} javascript/data_types -.-> lab-28293{{"`Factorial of Number`"}} javascript/arith_ops -.-> lab-28293{{"`Factorial of Number`"}} javascript/comp_ops -.-> lab-28293{{"`Factorial of Number`"}} javascript/error_handle -.-> lab-28293{{"`Factorial of Number`"}} end

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.

Other JavaScript Tutorials you may like