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 results

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Pass a positive integer modulus to the ModRing constructor.
  2. Ensure MOD is defined and > 0 before constructing the ring.
  3. 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

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


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/41549ce482af79b2. Report an issue: GitHub.