I was wondering how JavaScript handles modulo. For example, what would JavaScript evaluate 47 % 8
as? I can’t seem to find any documentation on it, and my skills on modulo aren’t the best.
Asked
Active
Viewed 3,341 times
1

Sebastian Simon
- 18,263
- 7
- 55
- 75

Elias Benevedes
- 363
- 1
- 8
- 26
4 Answers
3
Exactly as every language handles modulo: The remainder of X / Y
.
47 % 8 == 7
Also if you use a browser like Firefox + Firebug, Safari, Chrome, or even IE8+ you could test such an operation as quickly as hitting F12.

Owen Allen
- 11,348
- 9
- 51
- 63
-
1Note that *some* languages (notably C) treat `%` as a *remainder* operator rather than a *modulo* operator... http://stackoverflow.com/q/13683563/3651800 – Matt Coubrough Jul 08 '14 at 00:36
-
2This answer is incorrect in that modulo is not the same as remainder, JavaScript does indeed use `%` for remainder not modulo. This is not exactly the same as every other language: many do in fact use `%` for modulo – ljw Jun 16 '20 at 11:26
2
Javascript's modulo operator returns a negative number when given a negative number as input (on the left side).
14 % 5 // 4
15 % 5 // 0
-15 % 5 // -0
-14 % 5 // -4
(Note: negative zero is a distinct value in JavaScript and other languages with IEEE floats, but -0 === 0
so you usually don't have to worry about it.)
If you want a number that is always between 0 and a positive number that you specify, you can define a function like so:
function mod(n, m) {
return ((n % m) + m) % m;
}
mod(14, 5) // 4
mod(15, 5) // 4
mod(-15, 5) // 0
mod(-14, 5) // 1

1j01
- 3,714
- 2
- 29
- 30
0
TO better understand modulo here is how its built;
function modulo(num1, num2) {
if (typeof num1 != "number" || typeof num2 != "number"){
return NaN
}
var num1isneg=false
if (num1.toString().includes("-")){
num1isneg=true
}
num1=parseFloat(num1.toString().replace("-",""))
var leftover =parseFloat( ( parseFloat(num1/num2) - parseInt(num1/num2)) *num2)
console.log(leftover)
if (num1isneg){
var z = leftover.toString().split("")
z= ["-", ...z]
leftover = parseFloat(z.join(""))
}
return leftover
}

Grant mitchell
- 277
- 1
- 2
- 12