Skip to content

What is the purpose modulo operator in JavaScript

  • by

The modulo operator (% symbol) in JavaScript is used to find the remainder of dividing one number by another. It is commonly used for cyclic operations, like wrapping values around a range or checking if a number is even or odd.

For example, if you divide 7 by 3, you get a quotient of 2 and a remainder of 1. In JavaScript, you could express this using the modulo operator as follows:

7 % 3 // returns 1

The modulo operator is often used in programming to perform cyclic operations, such as wrapping values around a range of possible values. For example, if you want to increment a variable from 0 to 9 and then wrap it back to 0, you could use the modulo operator as follows:

let i = 0;
i = (i + 1) % 10; // i is now 1
i = (i + 1) % 10; // i is now 2
...
i = (i + 1) % 10; // i is now 0 (wraps around to the beginning of the range)

It also allows you to insert values into a string at specific placeholders or format specifiers.

let name = 'Alice';
let age = 25;
let message = 'Hello, my name is %s and I am %d years old.';
console.log(message % (name, age)); 

The template literals (introduced in ES6) are the preferred method for string formatting. Here’s an example of the same string formatting using template literals:

let name = 'Alice';
let age = 25;
let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);

JavaScript modulo operator example

Simple example code of purpose modulo operator in JavaScript

// Find the remainder of dividing two numbers
let a = 7;
let b = 3;
let remainder = a % b;
console.log(remainder);

// wrap a value around a range
let value = 8;
let range = 5;
value = value % range; 
console.log(value);

// check if a number is even or odd
let number = 7;
if (number % 2 === 0) {
  console.log('The number is even');
} else {
  console.log('The number is odd');
}

Output:

What is the purpose modulo operator in JavaScript

In the first example, we use the modulo operator to find the remainder of dividing a by b. In the second example, we use the modulo operator to wrap value around a range of range. In the third example, we use the modulo operator to check if number is even or odd.

Comment if you have any doubts or suggestions on this JS operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *