What's the Difference Between the JavaScript Remainder Operator and the Modulo Operator?

JavaScript Remainder Operator (%) vs. Modulo Operator

The % operator in JavaScript is actually the remainder operator, and not the modulo operator (in the traditional sense). Both, the remainder operator and modulo operator, produce the same result when the operands are of the same sign:

// 5 mod 3 = 2
// 5 rem 3 = 2

// -5 mod -3 = -2
// -5 rem -3 = -2

However, when the operands have different signs, their results differ:

// -5 mod 3 = 1
// -5 rem 3 = -2

// 5 mod -3 = -1
// 5 rem -3 = 2

Both are valid ways of calculating the modulo. In fact, they are calculated using the same basic formula:

Dividend - (Divisor * Quotient)

However, they differ in terms of how the quotient is calculated; "remainder" (in JavaScript and most other popular languages) uses truncated division whereas "modulo" typically refers to floored division. Due to this ambiguity (in how operands with different signs are handled), different programming languages draw the distinction between "remainder" and "modulo".

For example, consider the following function that can be used to calculate the remainder:

// ES6+
function rem(dividend, divisor) {
    const quotient = Math.trunc(dividend / divisor);
    return (dividend - (divisor * quotient));
}

console.log(rem(5, 3)); // 2
console.log(rem(-5, -3)); // -2
console.log(rem(-5, 3)); // -2
console.log(rem(5, -3)); // 2

This is the same as using the % operator in JavaScript (i.e. dividend % divisor):

console.log(5 % 3); // 2
console.log(-5 % -3); // -2
console.log(-5 % 3); // -2
console.log(5 % -3); // 2

Compare the "rem" function to the following "mod" function (which uses floored division):

function mod(dividend, divisor) {
    const quotient = Math.floor(dividend / divisor);
    return (dividend - (divisor * quotient));
}

console.log(mod(5, 3)); // 2
console.log(mod(-5, -3)); // -2
console.log(mod(-5, 3)); // 1
console.log(mod(5, -3)); // -1

In JavaScript, you can also achieve the same result with the remainder operator by using ((dividend % divisor) + divisor) % divisor, for example, like so:

console.log(((5 % 3) + 3) % 3); // 2
console.log(((-5 % -3) + -3) % -3); // -2
console.log(((-5 % 3) + 3) % 3); // 1
console.log(((5 % -3) + -3) % -3); // -1

Hope you found this post useful. It was published . Please show your love and support by sharing this post.