Search code examples
javascriptvariablesreturnincrementmodulus

JavaScript (erroneously?) only applying modulus to operation with this one syntax


I'm trying to increment a variable and return it to 0 if it hits a certain number. Logically I tried

i++ % number

but the variable kept incrementing.

I looked it up and found this answer, which works:

i = (i + 1) % 3

And I didn't understand why. They looked syntactically identical.

I then figured out that because of order of operations the modulus was operating first and then returning 1 (because 1 modulus anything is always 1)... and then just adding 1 to i.

There appears to be no way to circumvent this. Applying brackets only works if there's an operation to be done and it makes no difference if you wrap the number in brackets. So you can't apply brackets on i++ because it's shorthand and on i += 1 it makes no difference. You need to have (i + 1)

eg:

var i = 0;
var i2 = 0;
var i3 = 0;

$(document).click(function() {
  i++ % 3;
  i2 += 1 % 3;
  i3 = (i3 + 1) % 3;

  alert(i);
  alert(i2);
  alert(i3);
});

https://jsfiddle.net/z1wescrq/

Click on the output. The first 2 variables keep incrementing but the third one returns to 0 because it's doing the addition first.

Erroneous on JavaScript's part? er


Solution

  • i++ % 3;
    

    Let’s separate this line out into something equivalent that clearly shows the steps.

    var temp = i++;
    temp % 3;
    

    i++ increments i and evaluates to the previous value of i, which is stored in temp. You then evaluate temp % 3, and… do nothing with the result. It’s like writing this statement:

    2 + 2;
    

    It evaluates to 4 and does nothing with the 4. The difference with i = (i + 1) % 3 is that it calculates the modulus and then assigns it back to i instead of throwing it out.

    In short: no, this is not erroneous on JavaScript’s part.