2

im wondering, why int++ is not working, but int+1 is working. Someone have an idea why this happend in my example? Is there any difference?

function retryFunction(something, count) {
     if (!count) {
         count = 0;
     }

     console.log(typeof count);
     console.log(count);

     if (count < 5) {
          return setTimeout(function () {
              //working
              retryFunction(something, count+1);

              //not working
              retryFunction(something, count++);
          }, 1000)
      }
}

retryFunction(null);
  • 3
    (whatever "not working" means) because in the second case `count` is incemented *after* the call. – Federico klez Culloca Feb 22 '18 at 13:48
  • 1
    Possible duplicate of [What is the difference between "++" and "+= 1 " operators?](https://stackoverflow.com/questions/12988140/what-is-the-difference-between-and-1-operators) – Phiter Feb 22 '18 at 13:50
  • ↑ It's not the same language, but applies. – Phiter Feb 22 '18 at 13:50
  • 1
    Try ++count instead – Klaimmore Feb 22 '18 at 13:50
  • Possible duplicate of [Why doesn't the shorthand arithmetic operator ++ after the variable name return 2 in the following statement?](https://stackoverflow.com/questions/11218299/why-doesnt-the-shorthand-arithmetic-operator-after-the-variable-name-return) – Sohaib Shabbir بٹ Feb 22 '18 at 13:55

2 Answers2

5

The expression count + 1 adds 1 to count and "returns" the result of that.

The expression count++ returns the current value of count, and then adds 1 to count (thereby modifying the variable value, but after the old value was used).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Prefix increment vs. postfix increment operator. Speaking loosely in the context of your example, count++ says "call the function with the original value, then increment and store in the variable". If you were however to use ++count, this says "increment the variable and send the result to the function."

NB. Whilst ++count would "work", what you actually want is count + 1; it makes no sense to store the result in the passed parameter in this context.

Rab
  • 445
  • 4
  • 11