modulus operator javascript code example
Example 1: javascript division get remainder
var y=11;
var x=4;
var quotient = Math.floor(y/x);
var remainder = y % x;
Example 2: js modulo
function mod(n, m) {
return ((n % m) + m) % m;
}
Example 3: modulus js
const tableNumbers = [5, 14, 7, 10, 20, 11, 12, 15, 3]
for (let i =0; i < tableNumbers.length; i++) {
if (tableNumbers[i] % 2 === 0) {
console.log(tableNumbers[i])
}
}
Example 4: modulus js
console.log(10%3);
Example 5: how to find remainder in javascript
var myNum = 10 / 4;
var fraction = myNum % 1;
myNum = -20 / 7;
fraction = myNum % 1;
Example 6: mod remainder js
function mod(n, a, b) {
n = n | 0;
a = a | 0;
b = b | 0;
let rem;
if (a < 0 || b < 0) {
const places = (b - a);
rem = (n - a) % (places + 1);
rem = rem < 0 ? (rem + (places + 1)) : rem === 0 ? 0 : rem;
return rem - (places - b);
}
if (n === b) return n;
if (n === b + 1) return a;
if (n === a - 1) return b;
rem = n % (b || 1);
rem = rem < a ? (rem + b) : rem === 0 ? 0 : rem;
return rem;
}
mod(1, 1, 5);
mod(0, 1, 5);
mod(0, -1, 5);
mod(-2, -1, 5);