As part of a little home project I had the need for a recursive JavaScript call to build out a tree. Now recursion is a great tactic but easy to get into an infinite loop if you mess up. Now the code below looks good to me:

   function BuildNodes(resource)
   {
       var newdiv = document.createElement('div');
       var link = document.createElement('a');
       link.href= '#';
       link.innerText = resource.Name;
       link.onclick = function(){ ShowHideChildren(newdiv); }
       newdiv.appendChild(link);
       newdiv.style.paddingLeft = "15px"; 

      for(i=0; i< resource.Resources.length; i++)
     {
           newdiv.appendChild(BuildNodes(resource.Resources[i]));
     }
     return newdiv;
   }

But it gets stuck in an infinite loop. So far what I have figured is that the variable "i" is moving into a higher scope and causing this loop to keep resetting whenever a child was accessed.

Thankfully the fix was to put the 'var' keyword infront of 'i' which fixed the scope issue.

Before:    for(i=0; i< resource.Resources.length; i++)
After:      for(var i=0; i< resource.Resources.length; i++)

It seems kind of strange for this variable to be changed by calling itself but so far that is my theory. Any other thoughts on this one?