Javascript: Calling functions within functions and overwriting variables
<p>I have an array in JavaScript that can go as deep as I want:</p>

<pre><code> var steps = [
    { "step_id" : "1", "step_name" : "Step 1", "children" : 
        [ 
            { "step_id" : "4", "step_name" : "Step 4", "children" : 
                [ 
                    { "step_id" : "6", "step_name" : "Step 6" }
                ] 
             },
            { "step_id" : "5", "step_name" : "Step 5" } 
        ] 
    }, 
    { "step_id" : "2", "step_name" : "Step 2" }, 
    { "step_id" : "3", "step_name" : "Step 3" }
];
</code></pre>

<p>I then want to show each of the steps in a select drop down box. For every child step, I want to indent it. Here's my JS</p>

<pre><code> function stepsChildren(children, count) {
    var new_count = count + 1;
    var selection_values_children = '';
    for(j=0;j&lt;children.length;j++) {
        selection_values_children += '&lt;option value="' + children[j].step_id + '"&gt;';
        for(x=1;x&lt;=count;x++) {
            selection_values_children +='&amp;nbsp;&amp;nbsp;&amp;nbsp;';
        }
        selection_values_children += children[j].step_name + '&lt;/option&gt;';
        if (typeof(children[j].children) != 'undefined')
            selection_values_children += stepsChildren(children[j].children, new_count);
    }
    return selection_values_children;
}

var selection_values = '';
for(i=0;i&lt;steps.length;i++) {
    selection_values += '&lt;option value="' + steps[i].step_id + '"&gt;' + steps[i].step_name + '&lt;/option&gt;';
    if (typeof(steps[i].children) != 'undefined')
        selection_values += stepsChildren(steps[i].children, 1);
}

document.write('&lt;select&gt;' + selection_values + '&lt;/select&gt;');
</code></pre>

<p>This is almost working however in the <em>stepsChildren()</em> function the <em>j</em> variable gets overwritten every time I call it. It's almost like it's setting <em>j</em> as a global variable.</p>

<p>Am I making sense?</p>

<p>If not I've put together a sample for you to look at: <a href="http://jsfiddle.net/CJbnm/" rel="nofollow">http://jsfiddle.net/CJbnm/</a></p>

<p>If you run the code and look at the select box on the right, notice how Step 5 from the array is missing? </p>

<p>This is because there is only one child of Step 4 which updates the <em>j</em> variable to 1 instead of 2 for the parent function and doesn't show any more results...</p>
