0

How does the post increment operator work in a return statement of a function? Let say

function foo(n) {return n++}

If the return statement ends the function execution and returns n, then when does the increment of n happen? I suppose that n is incremented before the return statement. If so, then how does Javascript know to return n instead of n + 1;

kbl
  • 129
  • 5
  • As per [the definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#description), `n` is incremented after the return value has been used, not before `return` is executed. In your example that means `++` is useless, you can't access the changed value of `n`. – Teemu Aug 25 '23 at 05:59
  • But if n is returned, then no code in the function could be executed after the return statement. Now, where in the function is n incremented? – kbl Aug 25 '23 at 06:03
  • Not sure of this, but in a closure, which is destroyed after incrementing, or the operation is just ignored, because `n` is marked for garbage collection after `return`. – Teemu Aug 25 '23 at 06:06
  • 1
    This question seems to have been aggressively closed, since there doesn't seem to be an explanation of the "return" case in the linked article (although the general concept is explained). To provide more of an answer: I think this is due to a misconception that a "return" statement short-circuits all functionality. Returning a value does not instantly abort the function. The JS engine can still do the increment, although it's only useful in a case where the variable is not locally-scoped. – user995048 Aug 25 '23 at 06:22

0 Answers0