In JavaScript (and most C based languages) the Arithmetic operators are the following:
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Modulus: %
- Increment (x=x+1): ++
- Decrement (x=x-1): --
In mathematics the modulo operator basically finds the remainder, or modulus, of a number after it has been divided by a second number. So 10 % 3 = 1 reads 10 modulo 3 equals 1 and means that after 10 has been divided by 3 there is a remainder of 1 that cannot be divided by 3 without resulting in a floating point or decimal number. Here are a few examples:
- 57 % 2 = 1
- 75 % 10 = 5
- 33 % 3 = 0
- 4 % 4 = 0
- 0 % 2 = 0
- 2 % 0 = error: illegal division by zero
- 185 % 60 = 5
So how can you use this operator practically? Well, the previous examples are good and there are many more. However, the most common use for modulo is to determine whether a number is even or odd using the simple formula:
if x % 2 = 0 then "number is even"
else if x % 2 = 1 then "number is odd".
Some other uses are:
- to determine perfect squares
- making a clock that counts hours, minutes, and seconds (x % 60 = sec; Math.floor(x/60) % 60 = min)
- angle calculations (x % 360)
- non-destructive function for cryptology
- getting the decimal part of a number (x % 1)
- getting the day of the week from the day of the year ((x+offset) % 7)
I hope this tutorial has shown you how useful modulo can be and that you can use this in your programming.