1

I have a question about JS increment(++). I know many people here asked about ++ and +1 difference in JS but none of them mentioned it in recursive call sentence.

QUESTION: I want to call function exec inside exec function recursively but the flowing script is not working well.

var exec = function(index){
    if(index<7){
        exec(index++);
    }
}
exec(0);

output: Uncaught RangeError: Maximum call stack size exceeded

So I changed my script to the below and it worked well.

var exec = function(index){
    if(index<7){
        exec(index+=1);
    }
}
exec(0);

Why it acts like differenctly in this example? Is my recursive call wrong?

Dexygen
  • 12,287
  • 13
  • 80
  • 147
steve
  • 127
  • 12
  • 3
    This looks like a question about postincrement vs preincrement `++i` vs `i++`. If you try `++i` it should work. – elclanrs Jan 12 '18 at 01:56
  • 1
    In this case you should probably just be using `i+1` – david Jan 12 '18 at 01:57
  • @raina77ow This question has nothing to do with optimization. That duplicate question is about which to use in loops for performance reasons. – Barmar Jan 12 '18 at 01:59
  • 1
    Related questions: [one](https://stackoverflow.com/questions/25318554/javascript-how-does-i-work), [two](https://stackoverflow.com/questions/23930661/pre-increment-in-javascript), [three](https://stackoverflow.com/questions/971312/why-avoid-increment-and-decrement-operators-in-javascript). Still not sure this one's better than the rest. ) – raina77ow Jan 12 '18 at 02:05

2 Answers2

3

index++ is post-increment. That means it increments the variable, but the value of the expression is the old value. So:

exec(index++);

is equivalent to:

var oldindex = index;
index += 1;
exec(oldindex);

So the recursive call uses the old value, which means you keep calling recursively with the same value, and never hit the limit that stops recursing.

You need to use pre-increment, which increments the variable and returns the new value:

exec(++index);

Actually, there's no reason to increment the variable at all, since you never uses it again in that function. Just do:

exec(index + 1);
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

The issue with index++ is that it is a post-increment, so it only increments the value of index after it's already been passed back into exec. Using the pre-increment (++index) should work, since it will then increment it before passing it into the recursive call.

var exec = function(index){
    console.log(index)
    if(index<7){
        exec(++index);
    }
}
exec(0);
CRice
  • 29,968
  • 4
  • 57
  • 70