What is recursion in Js?

Hi, this in this post I’m going to explain you what is recursion in Javascript and why so important to use in some cases.

Recursive functions let you perform a unit of work multiple times and also recursion iswhen a function calls itself then this is called recursion.

Look, let suppose that we have this function that print ‘Hello there!‘ just that

// Function that print "Hello there!"
function sayHello() {
    console.log('Hello there!');
}

// Calling (executing) the function
sayHello();

Result:

Nice, so as I said recursion is when a function call itself, in this case we can call again our function inside of herself, look:

// Function that print "Hello there!"
function sayHello() {
    console.log('Hello there!');

    // Function call itself second time, third time, four time......infinite
    sayHello();
}

// Calling (executing) the function
// First time calling
sayHello();

Result: Wow! we have an infinite loop! oh no! our browser is blocked 🙁

Note: If you are trying this example, close your browser.

Ok, the reason why the browser is blocked is because our function sayHello() is been called again and again, again, again….etc. and that is not good so the next part is implement some type of condition that help us to stop our execution or help to execute the function certain times.

So, let’s change a little beat our code, let suppose that our function sayHello receive a 0 number as parameter and then every time that the function call itself this number (counter) will be incremented by one. Like this:

// Function that print "Hello there!"
function sayHello(counter) {
    console.log('Hello there! --->', counter); // 0, 1, 2, 3, 4, 5, 6.......infinite

    // Function call itself second time, third time, four time......infinite
    sayHello(counter + 1);
}

// Calling (executing) the function
// First time calling
sayHello(0);

Result: again this will cause a infinite loop with console as 0, 1, 2, 3…..infinite numbers. So to stop this we can implement some type of condition that help us to stop our execution, like this:

// Function that print "Hello there!"
function sayHello(counter) {
    console.log('Hello there! --->', counter); // 0, 1, 2, 3, 4, 5, 6.......infinite

    if (counter < 10) {
        // Function call itself just 10 times, no more.
        sayHello(counter + 1);
    }
}

// Calling (executing) the function
// First time calling
sayHello(0);

Result:

Nice, now our browser is not blocked and we have the results that we want (until 10) and we are using “recursion”.

If you understand this post then the next post will be very easy post for you to understand why “recursion” is so important in to real JS code.

By Cristina Rojas.