Logo HeaderGraphic
"... A Yankee in the Land of The Long White Cloud, Aotearoa ..."

Recursive Function Calls in JavaScript 

So recursion is one of my favourite programming structures, it’s elegant and fun to think thru.  but I just discovered a little bit of a nasty issue with JavaScript and Recursion.  Global Variables.

So here is my example html

<div id="outer" class="modifyMe">
	<div id="OuterChild1" class="modifyMe">
	
	</div>

	<div id="OuterChild2" class="noModify">
	
	</div>
	
	<div id="OuterChild3" class="modifyMe">
		
		<div id="InnerChild1" class="noModify">
		
		</div>
		<div id="InnerChild2" class="modifyMe">
		
		</div>
		<div id="InnerChild3" class="modifyMe">
		
			<div id="Child1" class="modifyMe">
			
			</div>
			<div id="Child2" class="modifyMe">
			
			</div>
			<div id="Child3" class="noModify">
			
			</div>
			
		</div>

	</div>
	
</div>

Now I want to loop thru the divs and makes some modification.  I want to modify each div (starting from the outside div) and those items that have a class of “modifyMe” need to be modified.  And the level of child nesting is not know (here it is just 3 levels, but it could be 5 or 10 or none).  Here is the recursive algorithm I came up with (simplified for this tutorial).

function modifyDiv( divToModify ){

	if( divToModify.className.search(/modifyMe/) > -1 ) {
		//make my modifications
	}
	
	for ( i = 0 ; i < divToModify.childNodes.length ; i++ ) {
		modifyDiv( divToModify.childNodes[i] );
	}
	
}

That’s how I would do it in C# or VB or C++, so that’s what I coded up.  Of course, that didn’t work.  The problem is, that each recursive call resets the i back to 0.  The first child will process just fine, the next child however…

As we loop thru the “outer”’s children,


   we successfully process the OuterChild1 (1=0)
   then we bubble back up to processing the children of outer (i++ to process 2nd child; i=1)
   then have a recursive call to process OuterChild2, and during THAT loop to attempt to process OuterChild2’s children, the i is set to 0 as it enters the loop and there is no children to process
   We bubble back up to processing the children of outer BUT when we were last processing the children of outer, the i was equal to 1, but now, i has been set to 0 from the recursive call)so the i++ that happens now doesn’t set i to 2 as it should to properly complete the job, no it set’s it to 1 and around the loop we go  

Of course, once I realised the issue, the fix wasn’t that hard, (hint use the “divToModify.nextSibling)  but still, if there was one thing I wish I could specify needs to be added to the JavaScript specification it would be scoping of variables!

Technorati Tags: ,
Digg This
 
Posted on 24-Mar-09 by Matthew C. Hintzen
Bookmark this post with:        
Tags: JavaScript, Development, Cold Pricklies, Raw Debugging Entry