Representing a recursive data structure as HTML DIVs I am using the following code which recursively executes function findWpisInZone(), code works fine, I just wondering if there is any better way to do it in JS,

DomBuilder.prototype = {
            domTree: '',
            findWpis: function () {
                var dataState = dojo.global.xxx.state.data,
                    scope = this;
                for (var zone in dataState) {
                    for (var wpi in dataState[zone]) {
                        this.domTree += '&lt;div data-xxx-type="{0}"&gt;'.format(zone);
                        findWpisInZone(dataState[zone][wpi]);
                        this.domTree += '&lt;/div&gt;';
                    }
                }
                function findWpisInZone(wpi, type) {
                    scope.domTree += '&lt;div data-xxx-type="{0}"&gt;'.format(wpi.wpi.webpart_cid);
                    for (var zone in wpi.zones) {
                        scope.domTree += '&lt;div data-xxx-type="{0}"&gt;'.format(zone)
                        for (var wpiInner in wpi.zones[zone]) {
                            // recursion search
                            findWpisInZone(wpi.zones[zone][wpiInner], type);
                        }
                        scope.domTree += '&lt;/div&gt;';
                    }
                    scope.domTree += '&lt;/div&gt;';
                }
            },
I think what you've got here is looking pretty fine. You could move the comment explaining that it's recursive to the function header if you want it to be more explicit. The recursive function isn't doing anything strange, though.

Usually, with recursion, one can unroll the recursion to be iteration instead.

I wouldn't recommend that in this case. Right now, you have about 10-12 lines, depending on how you count. It's just two forloops. The whole function can be summarized as "make a div that contains, for each wpi zone, another div containing it's sub wpi's, similar to the div we make now."

If you were to unroll this recursion then it would get messy.

You did well.



Possible improvements are assigning the strings to separate constants, and perhaps storing wpi.zones[zone] in a local store to reduce a double double array access for each for-loop iteration to a double single array access (the for loop accesses [zone][0] and [zone][wpiInner], by storing [zone] locally, you reduce the accesses to [0] and [wpiInner] instead).