TheAlgorithms/JavaScript · error · TypeError

Argument should be string

Error message

Argument should be string

What it means

Thrown by upper() in String/Upper.js when typeof str !== 'string'. A TypeError guarding the .replace(/[a-z]/g, ...) call which manually subtracts 32 from charCodeAt to shift lowercase ASCII to uppercase. Non-string input would either lack .replace or produce wrong results, so the type is enforced up front.

Source

Thrown at String/Upper.js:11

/**
 * @function upper
 * @description Will convert the entire string to uppercase letters.
 * @param {String} str - The input string
 * @return {String} Uppercase string
 * @example upper("hello") => HELLO
 * @example upper("He_llo") => HE_LLO
 */
const upper = (str) => {
  if (typeof str !== 'string') {
    throw new TypeError('Argument should be string')
  }

  return str.replace(/[a-z]/g, (char) =>
    String.fromCharCode(char.charCodeAt() - 32)
  )
}

export default upper

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Pass a primitive string: upper('hello').
  2. Coerce non-string inputs: upper(String(value)).
  3. Avoid the boxed String constructor (new String('x') is typeof 'object' and will throw).
  4. Prefer the native str.toUpperCase() when you do not specifically need this implementation.

Example fix

// before
const up = upper(input) // input is sometimes a number from a form field

// after
const up = upper(typeof input === 'string' ? input : String(input))
Defensive patterns

Strategy: type-guard

Validate before calling

function upperSafe(v) {
  if (typeof v !== 'string') throw new TypeError('Argument should be string')
  return upper(v)
}

Type guard

const isString = (v) => typeof v === 'string'

Try / catch

try { upper(s) } catch (e) { if (e instanceof TypeError) s = String(s); else throw e }

Prevention

When it happens

Trigger: Calling upper(123), upper(null), upper(undefined), upper(['abc']), upper({0:'a',length:1}), upper(Symbol('x')). Empty string upper('') does NOT throw — returns ''.

Common situations: Forwarding a number from a numeric form field without String(); passing a value from a Map/WeakMap lookup that returned undefined; a variable shadowed by a reassignment to a non-string; treating Buffer contents as a string without .toString().

Related errors


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