rod_torres
rod_torres

Reputation: 346

complete a recursive function in javascript

I have something like this:

function recurse(a){
  for(i = a; i < 3; i++){
    alert(i);
    if(i == 0){
      recurse(++a);
    }
  }
} 
recurse(0);

the output that i would expect is 0 (calls the new function) 1, 2 (ends the second function called), and then finishes the first run of the function with 1 and 2. But instead it only alert 0,1 and 2 once and it finishes.

Upvotes: 2

Views: 199

Answers (1)

Tim Goodman
Tim Goodman

Reputation: 23976

i is global

Try var i, and you may get the behavior you're expecting.

function recurse(a){
  for(var i = a; i < 3; i++){
    alert(i);
    if(i == 0){
      recurse(++a);
    }
  }
} 
recurse(0);

outputs: 0, 1, 2, 1, 2

the first 1, 2 being from the deeper level of recursion.

As originally written, you'd get 0 from the top level, 1,2 from the deeper level, and then nothing else in the top level (because i < 3 was no longer satisfied).

Upvotes: 2

Related Questions