Home

Modulo(remainder) operator in JavaScript

The modulo (%) operator in JavaScript works the same as it will in any other programming languages.

It is used to get the remainder of any division of two numbers.

console.log(5 % 2); // Output → 1

console.log(10 % 2); // Output → 0

console.log(17 % 3); // Output → 2

Uses of the modulo operator

The modulo operator is used to find whether a given number is even or odd.

// Filter the even numbers out of an array
const arr = [12, 454, 57, 6, 7, 974, 31, 7, 8, 43, 4, 7, 34, 94, 79];

console.log(arr.filter(n => n % 2 == 0));
// Output → [12, 454, 6, 974, 8, 4, 34, 94]
// Cycle through array '3' times
const arr = ['a', 'b', 'c'];

for (i = 0; i < arr.length * 3; i++) {
  const index = i % arr.length;
  console.log(arr[index]);
}
// Output:
// a
// b
// c
// a
// b
// c
// a
// b
// c


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments