Skip to main content

Command Palette

Search for a command to run...

What's different on % operator on Javascript?

Updated
3 min readView as Markdown

The Mathematical modulo operation

For positive numbers

  • The modulo operator is used to find the remainder when the dividend is divided by the divisor (dividend/divisor).
  • Let us say the dividend 'a' and the divisor 'n'. The remainder of a % n is given as r = a % n.
  • The remainder values will follow the pattern {0, 1, 2,.. (n-1), 0, 1, 2,.. (n-1), 0, 1..} for 'n' > 0. And for 'n' < 0 it will be like {0, -1, -2,.. -(n-1), 0, -1, -2,.. -(n-1), 0, -1..}.
  • Eg: (a % 3) will yield the remainder {0, 1, 2, 0, 1, 2...}. Where a >= 0.
  • Mathematically the formula can be given as a = q * n + r where 'a' is the dividend, 'q' is the quotient, 'n' is the divisor and 'r' is the remainder.
  • Eg: (10 % 3) is 1. Here a = '10', n = '3' and r = '1'.

For negative numbers

  • For negative numbers Eg: -17 % 10 gives 3 where a = -17, b = 10 and r = 3
  • Let us use the above formula.
    • a = q * n + r.
    • -17 = q * 10 + r. To obtain -17 on LHS we have to substitute a negative 'q' value because n is greater than 0, so the 'r' value should lie between {0, 1, 2, ...9}.
    • Here we can choose '-2' as the value of 'q' and '3' as the value for r.
    • -17 = (-2) * 10 + 3 => LHS = RHS.
  • This is how the we mathematically calculate the remainder of the two divided numbers.

How it works on Javascript?

  • In Javascript the % is known as remainder operator and not an modulo operator. Let us see why.
  • Here for the positive values the remainder of the two dividing numbers is obtained in a same method as discussed above.
  • But for the negative values, if and only if the dividend is negative, javascript will calculate the remainder value same like for the two positive values and adds a negative sign infront of it.
  • Eg: (-17 % 10) gives -7
    • It will evaluate the above expression as (17 % 10) which will give 7 as remainder and adds a '-' sign in front of it. If the divisor is negative the negative sign is ignored.
    • Eg: (-17 % 10) gives -7, (17 % -10) gives 7.

Mathematical modulo operation on Javascript

  • To perform the mathematical modulo operation we have use the formula
    r = ((a % n)+n) % n.
  • Eg: (-17 % 10) in javascript is given as ((-17% 10)+10) % 10 which gives 3 as remainder 'r'. Here a = -17 and n = 10.

Thanks for spending time to read this blog. Please leave your feedbacks and comments. If anyone who knows why javascript works in this kind of way for remainder operator please let me know on the comments.