DEV Community

Denise Pen
Denise Pen

Posted on

Recursion

What Is Recursion

Recursion is a process that calls itself. With respect to programming, recursion is a function that calls itself.

How Does It Work?
A recursive function calls itself until it reaches the base case.

The base case is where the recursion ends. Without the base case your function would not know when to stop calling itself. Once the base case is reached the function stops calling itself and returns its final value.

Let's Look At An Example
Let's look at the following example of recursion:

Imgur

We have a function that counts down from the number given to the function as an argument, until it gets to 1.

The base case instructs the function to return once the number has reached 1
( <=0 ).

The remainder of the function prints out the current value of the number and then decrements it before the countdown function is called again.

This cycle repeats until the number has reached the base case, at which point it prints out "You've reached the end" and the returns and exits the function.

Let's execute the function with a number:

countdown(4);

=> 4
=> 3
=> 2
=> 1
=> You've reached the end
Enter fullscreen mode Exit fullscreen mode

The above function could have been solved with a simple for loop as well:

function countdown(num) {
    for (let i = num; i > 0; i--) {
        console.log(i)
    }
    console.log("You've reached the end")
}

Enter fullscreen mode Exit fullscreen mode

As you can see for this simple example the for loop is much easier to use and understand. However, it is important to become familiar with recursion because is is used extensively in programming. Also, recursion comes up frequently in technical job interviews so take the time now to learn it.

Top comments (1)

Collapse
 
itsasine profile image
ItsASine (Kayla) • Edited