Why recursion Js is so important?

Hi, in the las post I explained What is recursion in Js? and in this post I’m going to show you a real JS example of how “recursion” can help you to solve some problems.

Nice!, so as I said: “Recursive functions let you perform a unit of work multiple times and also recursion is when a function calls itself then this is called recursion.

So, in real life we can have an object structure that have a repeated pattern in that case we can use a recursion to obtain some results about that repeated patter.

In this case myTree is an object and I want to obtain all the values of the titles that are in this entire object. Now we can see how title ‘A’ is node of myTree and inside of children that is an array of objects we have again the title node and so on.

For this cases when we have some patterns that are repeated we can use “recursion” see function getTitles(tree) {} comments.

// myTree is a object structure that have the title properties
const myTree = {
    title: 'A',
    children: [
        {
            title: 'B',
            children: [
                {
                    title: 'C'
                }
            ]
        },
        {
            title: 'D'
        }
    ]
};

// Function that get titles 
function getTitles(tree) {
    // Printing the title property value
    console.log('Title is: ', tree.title);

    if (tree.children) { // If my tree object have the property .children then

        // because children is an array we can use forEach method
        tree.children.forEach((child) => { // Go to every element that is inside the children array
            // Function call itself 
            getTitles(child);
        });
    }
}

// Executing the function first time
getTitles(myTree);

Result:

Nice, now we know how recursion can help us to solve problems in JS.

By Cristina Rojas.