DEV Community

Victor Peter
Victor Peter

Posted on

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.

Top comments (0)