The remainder operator in JavaScript is used to get the remaining value when an operand is divided by another operand. In some languages, % is considered modulo. Modulo and Remainder work differently when the sign of both operands is different.
In JavaScript remainder takes the sign of the dividend and to get modulo ((a % n) + n) % n should be used instead of a % n.
Syntax
remainder = var1 % var2
Example 1: This example returns the positive remainder in this case both modulo and remainder will be the same as both operands are positive.
Javascript
<script>
var a =4
var n = 2
var rem = a%n
var mod = ((a%n)+n)%n
console.log("Remainder is "+rem)
console.log("Modulo is "+mod)
</script>
|
Output:
"Remainder is 0"
"Modulo is 0"
Example 2: This example returns a negative remainder as the dividend is negative.
Javascript
<script>
var a =-4
var n = 2
var rem = a%n
var mod = ((a%n)+n)%n
console.log(rem)
console.log(mod)
</script>
|
Output:
-0
0
Example 3: Remainder with Infinity and NaN
Javascript
<script>
console.log(NaN%NaN)
console.log(NaN%2)
console.log(NaN%Infinity)
console.log(Infinity%NaN)
console.log(Infinity%Infinity)
console.log(Infinity%5)
</script>
|
Output:
NaN
NaN
NaN
NaN
NaN
NaN
We have a complete list of Javascript Operators, to check those please go through the Javascript Operators Complete Reference article.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Last Updated :
06 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...