Modulo oblongata

The modulo (or modulus) operator % returns the remainder of a division operation.

3 % 0 === NaN (cannot divide by 0)
3 % 1 === 0 (3 remainder 0)
3 % 2 === 1 (1 remainder 1)
3 % 3 === 0 (1 remainder 0)
3 % 4 === 3 (0 remainder 3)

A classic use case for the modulo operator is to check whether a number is even.

const isEven = number => number % 2 === 0

console.log(isEven(4)) // returns true
console.log(isEven(5)) // returns false

In the example above, a function takes in a number and checks to see if the remainder is equal to zero. If the remainder is anything other than zero, then the function returns false (the number is odd), otherwise it returns true (the number is even).

Another use case might be to get every Nth element of an array of unknown length.

const arr1 = [1,2,3,4,5,6,7,8,9,10]
const n = 3
const arr2 = arr1.filter((element, index) => (index + 1) % n === 0)
console.log(arr2) // return [3,6,9]

In this example, a second array is created by filtering through the first array and returning only the elements with an index (+1) that is perfectly divisible by 3. Therefore only every third element from the original array is added to the new array.

Leave a Comment