TheAlgorithms/JavaScript · error · TypeError

Coefficient a, b should be number

Error message

Coefficient a, b should be number

What it means

Thrown by isCorrectFormat() in the Affine cipher when coefficient a or b is not of type 'number'. Affine encryption computes (a*x + b) mod 26, which requires numeric arithmetic; passing a string/undefined/null would yield NaN ciphertext silently, so it is rejected.

Source

Thrown at Ciphers/AffineCipher.js:41

 * @param {Number} m - Modulos value
 * @return {Number} Return modular multiplicative inverse of coefficient a and modulos m
 */
function inverseMod(a, m) {
  for (let x = 1; x < m; x++) {
    if (mod(a * x, m) === 1) return x
  }
}

/**
 * Argument validation
 * @param {String} str - String to be checked
 * @param {Number} a - A coefficient to be checked
 * @param {Number} b - B coefficient to be checked
 * @return {Boolean} Result of the checking
 */
function isCorrectFormat(str, a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Coefficient a, b should be number')
  }

  if (typeof str !== 'string') {
    throw new TypeError('Argument str should be String')
  }

  if (!CoPrimeCheck(a, 26)) {
    throw new Error(a + ' is not coprime of 26')
  }

  return true
}

/**
 * Find character index based on ASCII order
 * @param {String} char - Character index to be found
 * @return {Boolean} Character index
 */

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Pass numeric literals: encrypt(text, 5, 8).
  2. Convert string sources with Number()/parseInt before calling.
  3. Destructure with explicit numeric defaults.

Example fix

// before
encrypt(text, formData.a, formData.b) // strings
// after
encrypt(text, Number(formData.a), Number(formData.b))
Defensive patterns

Strategy: type-guard

Validate before calling

function affineSafe(text, a, b) {
  return encrypt(text, Number(a), Number(b));
}

Type guard

/** @param {unknown} x @returns {x is number} */
const isNum = x => typeof x === 'number' && !Number.isNaN(x);

Try / catch

try { return encrypt(text, a, b); }
catch (e) {
  if (e instanceof TypeError && /Coefficient/.test(e.message)) {
    return encrypt(text, Number(a), Number(b));
  }
  throw e;
}

Prevention

When it happens

Trigger: Passing a = "5" (string), b = undefined, either coefficient omitted, or values pulled from inputs without conversion.

Common situations: Form input values (strings), destructuring that left a coefficient undefined, or a default-argument refactor that dropped a value.

Related errors


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