1

I was just testing this on javascript and noticed that each time I return a variable with a ++, it didn't return the new number. I know the ++ is added after, but shouldn't be added before returning it. When I debugged it, is showing the correct number, but when returning it doesn't. Does the interpreter executes this line after the return? If it's like that why the debugger shows the correct value?

This function returns the correct number without the ++. It returns 10.

function test(){
  var counter=0;
  for(i=0;i<10;i++){
    counter++;
  }
  return counter;
}

This other function, I thought it should return 11, but it doesn't it returns 10.

function test1(){
  var counter=0;
  for(i=0;i<10;i++){
    counter++;
  }
  return counter++;
}

Demo showing this example.

Diego
  • 916
  • 1
  • 13
  • 36

3 Answers3

1

counter++ is a post increment operator. It first perform the operation with current value after that it increments the value.

you should youse ++counter pre increpent operator.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • Yes I got it, but why on the debugger is showing the correct number? And at the moment of returning it doesn't? – Diego Jul 16 '14 at 04:14
  • @Diego I think that's because after just return it would have incremented the value of `counter`. – Mritunjay Jul 16 '14 at 04:15
  • that's actual funny and confusing how the debugger shows the result – Diego Jul 16 '14 at 04:17
  • @Diego may be but that's what `post incremtnt` works, after executing the `expression` immediately increment the value. – Mritunjay Jul 16 '14 at 04:18
0
function test1(){
  var counter=0;
  for(i=0;i<10;i++){
    counter++;
  }
  return ++counter;
}

By moving the ++ in front, it affects the variable before it's returned.

frenchie
  • 51,731
  • 109
  • 304
  • 510
Zane Helton
  • 1,044
  • 1
  • 14
  • 34
0

++ increments the number after the line it's on executes. So if you check your counter variable afterwards, it will be 11, but at the time when you're returning it, it's 10. Use "++counter" if you want to increment before returning.

phette23
  • 413
  • 4
  • 11