TheAlgorithms/JavaScript · error · Error
Modulus must be initialized in the object constructor
Error message
Modulus must be initialized in the object constructor
What it means
ModRing is a class for modular arithmetic operations. The constructor stores MOD, and isInputValid checks that MOD is truthy before performing arithmetic. Note: the check `!this.MOD` also rejects MOD=0, which is mathematically correct (modulus 0 is undefined) but the error message emphasizes initialization rather than the zero case.
Source
Thrown at Maths/ModularArithmetic.js:17
import { extendedEuclideanGCD } from './ExtendedEuclideanGCD'
/**
* https://brilliant.org/wiki/modular-arithmetic/
* @param {Number} arg1 first argument
* @param {Number} arg2 second argument
* @returns {Number}
*/
export class ModRing {
constructor(MOD) {
this.MOD = MOD
}
isInputValid = (arg1, arg2) => {
if (!this.MOD) {
throw new Error('Modulus must be initialized in the object constructor')
}
if (typeof arg1 !== 'number' || typeof arg2 !== 'number') {
throw new TypeError('Input must be Numbers')
}
}
/**
* Modulus is Distributive property,
* As a result, we separate it into numbers in order to keep it within MOD's range
*/
add = (arg1, arg2) => {
this.isInputValid(arg1, arg2)
return ((arg1 % this.MOD) + (arg2 % this.MOD)) % this.MOD
}
subtract = (arg1, arg2) => {
this.isInputValid(arg1, arg2)
// An extra MOD is added to check negative resultsView on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a positive integer modulus to the ModRing constructor.
- Ensure MOD is defined and > 0 before constructing the ring.
- Validate the config value for modulus before creating the ModRing instance.
Example fix
// before const ring = new ModRing() ring.add(3, 5) // after const ring = new ModRing(7) ring.add(3, 5)
Defensive patterns
Strategy: validation
Validate before calling
if (typeof modulus !== 'number' || modulus <= 0) {
throw new RangeError('modulus must be a positive number')
}
const ring = new ModRing(modulus) Prevention
- Always pass a positive integer modulus to the ModRing constructor.
- Validate config values for modulus before constructing the ring instance.
- Remember that MOD=0 is rejected; modulus must be strictly positive.
When it happens
Trigger: Calling new ModRing() with no argument (MOD is undefined), new ModRing(0), new ModRing(null), then invoking any method like add, subtract, etc.
Common situations: Constructor called without arguments, MOD read from a config file that is missing or empty, or MOD=0 from a failed parseInt.
Related errors
- Number must be greater than zero.
- Number must be greater than zero.
- Number must be greater than zero.
- Index cannot be Negative
- Index cannot be a Decimal
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/41549ce482af79b2.
Report an issue: GitHub.