5.6 Where are rem and mod used in programming languages?

5.6.1 JavaScript’s % operator computes the remainder

For example (Node.js REPL):

  1. > 7 % 6
  2. 1
  3. > -7 % 6
  4. -1

5.6.2 Python’s % operator computes the modulus

For example (Python REPL):

  1. >>> 7 % 6
  2. 1
  3. >>> -7 % 6
  4. 5

5.6.3 Uses of the modulo operation in JavaScript

The ECMAScript specification uses modulo several times – for example:

  • To convert the operands of the >>> operator to unsigned 32-bit integers (x mod 2**32):

    1. > 2**32 >>> 0
    2. 0
    3. > (2**32)+1 >>> 0
    4. 1
    5. > (-1 >>> 0) === (2**32)-1
    6. true
  • To convert arbitrary numbers so that they fit into Typed Arrays. For example, x mod 2**8 is used to convert numbers to unsigned 8-bit integers (after first converting them to integers):

    1. const tarr = new Uint8Array(1);
    2. tarr[0] = 256;
    3. assert.equal(tarr[0], 0);
    4. tarr[0] = 257;
    5. assert.equal(tarr[0], 1);