Skip to content

Modulo of negative number gives negative result

Quick summary

You used % expecting a positive result, but with a negative dividend the result is negative — breaking index wrapping.

Why this happens

  • Using % to wrap array indices with a negative dividend

  • Assuming % behaves like mathematical modulo (always non-negative)

  • Computing clock or cyclic values with negative inputs

Minimal example

✗ Broken code
const idx = -1 % 5;
const arr = [0, 1, 2, 3, 4];
console.log(arr[idx]); // arr[-1] — undefined, expected arr[4]
✓ Fixed code
const idx = ((-1 % 5) + 5) % 5; // 4
const arr = [0, 1, 2, 3, 4];
console.log(arr[idx]); // 4 — correct wrap-around

-1 % 5 is -1 in JS (sign of dividend), so arr[-1] is undefined. The formula ((a % b) + b) % b gives the mathematical modulo 4, wrapping correctly.

How to diagnose

  • Print the result of a % b for negative a to see the sign

  • Check whether the result is used as an array index

  • Compare with the expected mathematical modulo

How to fix

  • Use ((a % b) + b) % b to get a non-negative modulo

  • Use Math.floorMod if available (not in JS — implement the formula)

  • Validate that the dividend is non-negative before using %

How to prevent

  • Use ((a % b) + b) % b for cyclic/wrapping arithmetic

  • Test modulo with negative inputs explicitly

Related Resources

Related Glossary

Related Lessons

← Back to language