2

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.

0

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.