What is recursion in javascript?

Recursion is a process of calling itself. A function that calls itself is called a recursive function.

Suppose that you have a function called ‘recurse()’. The recurse() is a recursive function if it calls itself inside its body

Example:

function recurse() {
	recurse();
}
recurse();

 

A recursive function always has a condition to stop calling itself.

Otherwise, it will call itself indefinitely.

Once the condition is met, the function stops calling itself. This is called a base condition.

So a recursive function looks like this:

function recurse() {
	if (condition){
		// stop calling itself
	} else {
		recurse();
	}
}
recurse();

 

To prevent infinite recursion, we can use if…else statement where one branch makes the recursive call, and the other doesn’t. As shown in above example.

Using recursive functions (Example):

Suppose that you need to develop a function that counts down from a specified number to 1.

For example, to count down from 5 to 1:

function countDown(Number) {
	console.log(Number);

	let nextNumber = Number - 1;

	if (nextNumber > 0) {
		countDown(nextNumber);
	}
}
countDown(5);

// Output-			5
//				4
//				3
//				2
//				1

 

In the above program, the user passes a number as an argument when calling a function.

In each iteration, the number value is decreased by 1 and the function countDown() is called until the number is positive.

Here, newNumber > 0 is the base condition.

When the number reaches 0, the base condition is met, and the function is not called anymore.

Fabio

Full Stack Developer / Entrepreneur

About the Author

I’m passionate about web development and design in all its forms, helping small businesses build and improve their online presence. I spend a lot of time learning new techniques and actively helping other people learn web development through a variety of help groups and writing tutorials for my blog about advancements in web design and development.

View Articles