Recursion in Javascript

Recursion in Javascript

In functional programming, recursion is an important topic. But what about newbie programmers? Is it problematic for them to understand the recursion and its working fundamentals? Well, within the blog, I'll try to make you understand the recursion and its working fundamentals to clarify its basic concepts.

What is Recursion?

Whenever a user searches for "recursion" in the Google search bar, he will get "did you mean: recursion" every time. Again, if you click the link suggested by Google for recursion, it will appear the same. This is all about recursion- calling something again and again.

Google Search on Recursion

Recursion is a process of repeating items in a self-similar way. In computer science, recursion is a method of solving a problem where the solution Depends on solving more minor instances of the same problem. The most common form of recursion is a function that calls itself.

Let’s understand with an example:-

function factorial(r) {
    if(r <= 0) return 1;
    else return r*factorial(r-1);
}
console.log(factorial(3));

Output:- 6

With the above code, we can get the factorial of a number. For reference- we have used the number 3 to get its factorial. The factorial of 3 will be 3 * 2 * 1 = 6.

By following the above function, one can get the factorial of a number.

Why use Recursion?

A lot of people have a hard time understanding recursion. And I get it – it can be confusing. But once you know it, it's simple and can be a potent tool. So why use recursion? Recursion can be used to solve problems that can't be solved using regular loops. It's beneficial for problems that involve processing data structures like trees and lists. And it can make your code a lot cleaner and easier to read. So if you're stuck on a problem, don't be afraid to try recursion. It just might be the answer you're looking for.

What is Recursive Function?

Recursive functions are one of the most powerful programming tools that a programmer can use. Recursive functions allow programmers to repeat the same function call on itself, which helps break down complex problems into simpler ones.

A recursive function is a function that calls itself. Recursion is a powerful problem-solving technique used in many different situations. For example, it could use a recursive function to calculate the factorial of large numbers or find all possible combinations from a set of objects.

How Does Javascript Recursion Work?

To understand how recursion works, let's look at the makeup of the syntax of the recursive functions. There are three essential parts of syntax; Anyone writing a recursive function must provide three crucial features of that syntax.

They are as follows:

  • The Function Declaration

  • The Base Case

  • The Recursive Call Command

Function Declaration

function recursion() {
}

The function declaration is a part that declares the intended recursive function. It is done the same way a new function is declared in Javascript.

The Base Case

It is the foundation of each recursive function. It is the fundamental unit of the initial problem to be solved when the issues or problems are broken down into smaller tasks.

The base case can be viewed as the command that terminates the recursive process if the specified command is valid. Some base cases can be enclosed in an if...else statement

For example-

function recursion() {
    // here is the base case
    if (true) {
        return;
    }
}

When the base case condition is met, the command with the return statement is executed.

The Recursive Call Command

This command or statement is liable for the stimulus of the recursive calls. Also, this command tackles the main essence of the problem you are attempting to solve. It is any generic JavaScript code, depending on the developer's goal.

function recursion() {
   // here is the base case
    if (true) {
        return;
    }
    // here is the recursion function codes
    return ... ;
}

You can directly call the function to run using the recursion() function when all these are implemented. The entire recursive process now looks like this;

function recursion() {
   // here is the base case
    if (true) {
        return;
    }
    // here are the recursion function codes
    return ... ;
}

recursion()

Common Recursion Examples using JavaScript

The examples within the blog are based on Javascript as the programming language. Nevertheless, the good news is that these concepts can also be applied to other programming languages.

This is all about recursion- a methodology to call itself.

What are Common Examples of Recursion using JavaScript?

How to find the factorial of a number

The first example users can use to understand recursion is the factorial of a number. As the name suggests, the factorial of a number should be returned by this function. For instance, 24 is the factorial of 4. The factorial of 0 should be interpreted as 1.

Javascript code to find the factorial of a number:-

I’ll walk you through the whole process or the logic involved in finding the factorial of a number using recursion in Javascript.

function factorial(x) 
{ 
  if (x === 0)
 {
    return 1;
 }
  return x * factorial(x-1);      
}
console.log(factorial(6));
Working of the code:-

When the number is 1, the factorial is also 1.

Logic -

number = 6

num * factorial(num - 1) means

6* (6-1) * (5-1) * (4-1) * (3-1 )* (2-1) * 1

= 6 * 5 * 4 * 3 * 2 * 1

= 720 - Output(The factorial of digit 6 is 720)

If you want to find the factorial of any other number per your choice, you can use the same code and replace it with your desired number to find its factorial value.

How to find the integers from the range (x and y)

A well-known example of recursion using Javascript is- finding or getting the integers between two numbers

Javascript code to get all the integers from the range (2 and 20):-
var range = function(start_num, end_num) 
{
  if (end_num - start_num === 2) 
  {
    return [start_num + 1];
  } 
  else 
  {
    var list = range(start_num, end_num - 1);
    list.push(end_num - 1);
    return list;
  }
};
console.log(range(2,20));
Working of code

Numbers:- (2 and 20)

Logic-

var range = function(start_num , end_num)

end_num - start_num === 2?

If Yes, return[start_num+1];

** If No,** var list = range(start_num , end_num-1); list.push(end_num-1); Return list;

**↓ **

End

Output:- [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Javascript code to find the exponent of a number

It should be noted that an exponent of a number indicates how many times the base number is multiplied. 9^2 = 9 x 9 = 81. In this instance, the exponent is 2, and the base is 9.

Program to find the exponent of a number
var exponent = function(a, n) 
{
   if (n === 0) 
   {
    return 1;
    }
  else 
  {
    return a * exponent(a, n-1);
  }
};

console.log(exponent(9, 2));
Working of code

Numbers:- (9 base and 2 exponents)

Logic-

var exponent = function(a , n)

n === 0?

If Yes, return 1;

** If No,** return a* exponent (a, n-1);

End

Output:- 81

Javascript program to find the greatest common divisor (GCD) of two positive numbers

Using Javascript, finding the GCD of two positive numbers is also considered the most common recursion example.

For instance:- Let’s consider two positive numbers, 4308 and 926.

Program to find the greatest common divisor (GCD) of two positive numbers:-
var gcd = function(a, b) {
    if ( ! b) {
        return a;
    }

    return gcd(b, a % b);
};
console.log(gcd(4308, 926));
Working of code

Numbers:- (Two positive numbers are 4308 and 926)

Logic-

var gcd = function(a , b)

! b ?

If Yes, return a;

** If No,** return gcd(b, a% b);

End

Output:- 2

Final Takeaway

So what does all this mean?

The above examples are of recursion using Javascript, and there are many more to learn. Thus, keep learning & growing as much as you can. If you find any code corrections or logical statement issues, please feel free to mention them in the comment section.

Did you find this article valuable?

Support Quokka Labs' Blogs by becoming a sponsor. Any amount is appreciated!