In JavaScript, the remainder operator (%) returns the remainder of a division operation between two numbers. It can be used to determine if a number is even or odd, among other practical applications.
dividend % divisor
Where dividend
is the number being divided and divisor
is the number being divided by. The %
symbol is the remainder operator.
Here’s an example:
let a = 7;
let b = 3;
let remainder = a % b;
console.log(remainder); // Output: 1
Since 7 divided by 3 is 2 with a remainder of 1, the value of remainder
will be 1.
JavaScript Remainder (%) Example
A simple example code uses the remainder operator (%) in JavaScript to determine whether a number is even or odd:
function isEven(number) {
return number % 2 === 0;
}
console.log(isEven(4)); // Output: true
console.log(isEven(7)); // Output: false
You can also use the remainder operator in other expressions, such as in conditional statements or loops:
number = 10
if (number % 2 === 0) {
console.log('The number is even.');
} else {
console.log('The number is odd.');
}
Output:
- The
if
statement tests whether the remainder of dividingnumber
by 2 is equal to 0. - If the remainder is 0 (i.e.,
number
is an even number), the code inside the first block of theif
statement will be executed, which in this case is to log the message “The number is even.” to the console. - If the remainder is not 0 (i.e.,
number
is an odd number), the code inside theelse
block will be executed instead, which logs the message “The number is odd.” to the console.
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