0

I am trying to make a function that will include a for-loop. However, in the loop, it calls itself and the "next layer" resets the counter. I know that this would work in PHP but I cannot figure out how to keep that counter "protected" from being reset by the inner for-loop.

My original code is more complicated, so I simplified the example to this:

function test(a=5){
  for(i=0; i<a; i++){
    console.log(i);
    test(a-1);
  }
}

test();

When I run this I get "1 1 1 1".

What I expect is "1 1 1 1 2 1 2 1 1 2 1 3 1 1 2 1 2 1 1 1 2 1 2 1 1 2 1 3 1 1 2 1 3 1 1 1 2 1 2 1 1 2 1 3 1 1 2 1 4 1 1 1 2 1 2 1 1 2 1 3 1 1 2 1" (tried the same function in PHP).

David Sojka
  • 73
  • 1
  • 9

1 Answers1

1

If you declare a variable with out var,let,const the variable will become a global variable. So in your code you are creating a global variable and then arr the recursive function have same i incremented.

You need to use let to declare i.

function test(a=5){
  for(let i=0; i<a; i++){
    console.log(i);
    test(a-1);
  }
}

test();
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73