Eric
Eric

Reputation: 603

Counting up recursively and using +1 vs ++

I have a basic question about recursion and how the difference of +1 and ++ affects the result.

Why is it that this code:

var arrayLoop = function(idx){
  if(idx < 5){
    console.log(idx);
     return arrayLoop(idx+1);
   }
};
arrayLoop(0);

will work just fine, but this:

var arrayLoop = function(idx){
  if(idx < 5){
    console.log(idx);
    return arrayLoop(idx++);
  }
};
arrayLoop(0);

results in an infinite loop?

Upvotes: 1

Views: 48

Answers (2)

Jack
Jack

Reputation: 133609

In the second example you have used ++ operator as post-increment, so you are using idx++ and not ++idx.

What happens is that with post-increment the expression is evaluated with the value before the increment, then it is increment. You can see it like sort of (mind that's not semantically identical, it's just to give you the idea):

return arrayLoop(idx);
idx = idx + 1;

So you can see that method is always invoked with 0 as argument.

The pre-increment ++idx operator would invert the operations:

idx = idx + 1;
return arrayLoop(idx);

Upvotes: 2

Burleigh Bear
Burleigh Bear

Reputation: 3314

i++ is an expression that increments 'i' but returns the value before the increment. You can use ++i to achieve your desired result.

Upvotes: 2

Related Questions