DEV Community

Michael Lobman
Michael Lobman

Posted on

Recursion in JavaScript

The concept of recursion sounds intimidating, but it is deceptively straightforward.

Let's dive in. First, the terminology.

The MDN Web Docs define recursion as:

The act of a function calling itself, recursion is used to solve problems that contain smaller sub-problems. A recursive function can receive two inputs: a base case (ends recursion) or a recursive case (resumes recursion).

Let's create a function called "recursiveFunction" with a "num" parameter, taking in a number as an argument. If "num" is less than 10, the function will call itself on num + 1, checking to see if the new value is less than 10.

If the value of "num" is NOT less than 10, our "else" statement will execute and console.log "num".

To ensure our code runs as anticipated, I will add in a console.log in the "if" statement as well.

function recursiveFunction(num){
    if (num < 10) {
        console.log(`Number = ${num}. recursiveFunction will be called.`)
        recursiveFunction(num+1)
    } else {
        console.log(`Number = ${num}. Recursion terminated.`)
    }
}
Enter fullscreen mode Exit fullscreen mode

In the abstract, recursion can seem needlessly verbose; however, when your code becomes more complex, recursion keeps your code clean.

For example, I created a recursive function for a React application that uses a window to display a random lyric from a hard-coded array:

function randomLyric(array) {
    let random = array[Math.floor(Math.random()*array.length)];
    if (lyric !== random) {
        setLyric(random);
    } else {
        randomLyric(array)
    }
}
Enter fullscreen mode Exit fullscreen mode

The "if" statement checks if the randomly pulled lyric stored in the "random" variable is different from the lyric that is already stored in the state variable "lyric". If it is indeed different, it will use the setter function setLyric to updated the state variable "lyric" to the random lyric.

If, however, the two lyrics are exactly equal to each other - that is, our randomly pulled lyric is already being displayed - the recursion inside the "else" block executes and calls the randomLyric function on the same array, repeating the process until the randomly generated lyric is indeed random.

Try making a simple recursive function yourself. Once you see the utility of a function calling itself if certain conditions are met, you will never look back.

Well, you will, but only recursively.

Happy coding.

Discussion (0)