Skip to content
Advertisement

Javascript recursive with for loop breaks the loop and does not finishes

I am writing a recursive function that needs to run in an array of objects with any level of deepness. (if it finds an array it will run into this array after finishing the object properties)

The idea is to create a generic table in a webpage that can handle any king of object structure and rendering elements respecting their hierarchy.

I can go any level deeper but it never finishes the loop:

JavaScript

See that it ends up after the first iteration in the first list without running into the next two objects.

Any insights?

thanks.

Advertisement

Answer

You shouldn’t use return when making the recursive call.

Also, avoid using global variables in recursive functions, it makes them non-reentrant. If you need data to persist and update, pass it as parameters and return values. You can use default values for the initial values.

In my rewrite, I pass counter as a parameter, and then return the updated value, which the caller assigns back to its counter. Similarly, I pass tempArr as a parameter.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement