TheAlgorithms/JavaScript · error · TypeError

Argument should be string

Error message

Argument should be string

What it means

ROT13 rejects non-string input because it calls str.replace(/[a-z]/gi, ...) and relies on charCodeAt. A non-string would coerce badly or throw a vaguer internal error, so the function validates the type up front.

Source

Thrown at Ciphers/ROT13.js:10

/**
 * @function ROT13
 * @description - ROT13 ("rotate by 13 places", sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. ROT13 is a special case of the Caesar cipher which was developed in ancient Rome. Because there are 26 letters (2×13) in the basic Latin alphabet, ROT13 is its own inverse; that is, to undo ROT13, the same algorithm is applied, so the same action can be used for encoding and decoding. The algorithm provides virtually no cryptographic security, and is often cited as a canonical example of weak encryption.
 * @see - [wiki](https://en.wikipedia.org/wiki/ROT13)
 * @param {String} str - string to be decrypted
 * @return {String} decrypted string
 */
function ROT13(str) {
  if (typeof str !== 'string') {
    throw new TypeError('Argument should be string')
  }

  return str.replace(/[a-z]/gi, (char) => {
    const charCode = char.charCodeAt()

    if (/[n-z]/i.test(char)) {
      return String.fromCharCode(charCode - 13)
    }

    return String.fromCharCode(charCode + 13)
  })
}

export default ROT13

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Pass a string: ROT13('hello').
  2. Wrap with String(value) when the source might be non-string.
  3. Decode Buffers with .toString('utf8').

Example fix

// before
ROT13(userId) // number
// after
ROT13(String(userId))
Defensive patterns

Strategy: type-guard

Validate before calling

function rot13Safe(v) {
  return ROT13(typeof v === 'string' ? v : String(v));
}

Type guard

/** @param {unknown} s @returns {s is string} */
const isString = s => typeof s === 'string';

Try / catch

try { return ROT13(text); }
catch (e) {
  if (e instanceof TypeError && /should be string/.test(e.message)) {
    return ROT13(String(text));
  }
  throw e;
}

Prevention

When it happens

Trigger: Passing a number, object, null, undefined, array, or Buffer instead of the text string.

Common situations: Passing a decoded-but-still-typed value, a Buffer from crypto/file input, or a value read from a typed array.

Related errors


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