DEV Community

Victor Peter
Victor Peter

Posted on

1

Factorial function in JavaScript (with recursion)

Introduction

This is a simple program that computes the factorial of a number using recursion.

So, what is Recursion? 🤨

Recursion in programming is a technique or method of writing a function in which that function calls itself until a specified condition is met.
Recursion can be used to repeat an action without using a for or while loop.

A Simple Factorial Function in JavaScript.

Factorial function in JavaScript

Line 3 and 8 will stop the function from calling itself (i.e stops the recursion) when the value of n is less than or equal to 1.
If n is still greater than one then line 4 and 9 will will be executed and as you can see line 4 and 9 still calls its respective functions, that's recursion in action 😁.

Here is the result:
The Result

Note: 🙏 ✍

Make sure the condition to break your recursion is valid. If the condition is not valid you will run into an infinite recursion, this means your recursion will run forever and ever (hope you didin't say Amen 🤣). Have fun.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more