Tuesday, November 16, 2021

How to use recursion in JavaScript? Example Tutorial

If you are a programmer, you may have come across a term called “recursion”. In programming, several techniques are used to solve a problem. Recursion is one such technique. It allows you to break a big problem into smaller parts and then solve those smaller parts. It's also one of the useful techniques to solve dynamic programming-based problems and that's why it's very very important for any programmer or developer preparing for coding interviews.  Recursion is not limited to a specific programming language. It can be performed using Java, JavaScript, C, or any other programming language. In this article, we will learn what is recursion and how to perform it using JavaScript.

What is recursion?

Recursion is a programming technique in which a function calls itself. In simple words, if a function is called inside its function body, it is called recursion.

In JavaScript, a function, once defined, can be called anywhere. For recursion, the function call has to be made within the body of the same function. For example, observe the following code.

function demoFun(){
  console.log("This is a demo function")
}
demoFun()


“demoFun” is a function with a console statement inside its body and in the end, it is being called. This is how a normal function is used.

function demoFun(){
console.log("This is a demo function")
  demoFun()
}
demoFun()

After the console statement inside the function body, a function call for the “demoFun” is made. Now, we have two function calls for “DemoFun”. 

When this code is executed, the function call outside the “demoFun” is executed and the function is invoked. When the execution enters the function body, the console statement is executed first, and after it, the function call inside it is made. Because of this, “demoFun” is invoked again. Then, the function is executed again because of the function call inside it. This happens again and again.

This is called recursion. The “demoFunc” is executing itself by making the function call within its body. But here is one problem.

This continuous cycle of calling the function within its body will result in an infinity loop. So to avoid such a situation, use a “leave event”.

Leave event is a control statement that is used to prevent the infinite loop. In simple terms, it’s a condition such as if statement, that breaks the execution.

Observe the following code.
function printNumbers(n) {
console.log(n);
if (n > 0) {
printNumbers(n - 1);
}
}

printNumbers(10);

“printNumber” is a recursive function. But, when executed, it won’t lead to an infinite loop because a “leave event” is defined in it.

if (n > 0) {
  printNumbers(n - 1);
}


So, in the first call, the value of n is 10. In the second call, the value is 9. So, with every recursive call, the value is decremented by 1. When the value is 0, the recursion ends because of the if statement.

Remember, whenever you are using recursion, place a condition that will break the recursion.
Factorial example

Let’s understand recursion in JavaScript with the help of an example.

In this example, we will calculate the factorial of a number using recursion.

function calculateFactorial(number) {
if (number == 0) {
return 1;
} else {
return number * calculateFactorial(number - 1);
}
}
let factorial = calculateFactorial(3);
console.log(factorial);


The return statement is often used with recursion. Following is how the factorial of 5 should be calculated.

5 * 4 * 3 * 2 * 1 = 120


In the “calculateFactorial” function, first, the value of the number is 5. In the second call, the value of number 4 and goes on decrementing until the value is 1. So, the “number” in the return statement is being multiplied by the value returning from the function call. Observe the following illustration.

5 * calculateFactorial(4) = 5 * 24; value returned = 120

4 * calculateFactorial(3) = 4 * 6; value returned = 24

3 * calculateFactorial(2) = 3 * 2; value returned = 6

2 * calculateFactorial(1) = 2 * 1; value returned = 2

1; value returned = 1


So the value needed at the moment is being calculated by the recursive function call. This is how recursion works. The above example might seem confusing but try to understand it again and again, and then only you will understand how recursion works. 

Recursion is also heavily used to solve problems related to a linked list, array, string, stack, tree, and graph data structure and numbers, mostly because they are recursive data structures. Knowing this fact can help you a lot during interviews. 

How to use recursion in JavaScript? Example Tutorial
 


Wrapping it up
It is fine if you don’t understand the recursion properly at the moment. Recursion is confusing and it takes time and practice to understand it properly. In this article, we discussed what is recursion and how to perform it in JavaScript. Though the factorial example is confusing, it is one of the best to understand the concept of recursion.

 
Other Important Resources for Coding and Programing Interviews:

P. S. - If you want to learn more about data structure, algorithms, and recursion then you can also check out these free data structure and algorithms courses to start with. They not only cover Recursion but also other important data structure and algorithms topics. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.