TheAlgorithms/JavaScript · error · TypeError

The given value is not a string

Error message

The given value is not a string

What it means

Thrown by ReverseStringIterative() in String/ReverseString.js when the argument's typeof is not 'string'. This is a TypeError (not a generic Error), signalling a programming contract violation rather than bad data. The function then iterates the string by index, so it must have a string input to subscript.

Source

Thrown at String/ReverseString.js:6

/**
 * A short example showing how to reverse a string.
 */
function ReverseStringIterative(string) {
  if (typeof string !== 'string') {
    throw new TypeError('The given value is not a string')
  }
  let reversedString = ''
  let index

  for (index = string.length - 1; index >= 0; index--) {
    reversedString += string[index]
  }

  return reversedString
}

/**
 *
 * @author dev-madhurendra
 * Reverses a number by converting it to a string.
 *
 * @param {string} str - The number to reverse.
 * @returns {string} The reversed number.

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Pass a primitive string: ReverseStringIterative('hello').
  2. If the source may be non-string, coerce explicitly: ReverseStringIterative(String(value)).
  3. Unbox boxed strings: if (value instanceof String) value = value.valueOf().
  4. Read the right property from your source (e.g. event.target.value, not event.target).

Example fix

// before
const out = ReverseStringIterative(inputEl) // inputEl is an HTMLElement, not its value

// after
const out = ReverseStringIterative(String(inputEl.value))
Defensive patterns

Strategy: type-guard

Validate before calling

function reverseSafe(v) {
  if (typeof v !== 'string') throw new TypeError('expected string')
  return ReverseStringIterative(v)
}

Type guard

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

Try / catch

try { ReverseStringIterative(input) }
catch (e) { if (e instanceof TypeError) { /* coerce and retry */ } else throw e }

Prevention

When it happens

Trigger: Calling ReverseStringIterative(42), ReverseStringIterative(null), ReverseStringIterative(undefined), ReverseStringIterative(['a','b']), ReverseStringIterative({}). Note: a String object (new String('x')) would also throw because typeof is 'object'.

Common situations: Forwarding DOM node values or event targets without reading .value/.textContent; passing a Buffer in Node; receiving parsed JSON where a field was numeric; using the boxed String constructor new String('hi') which yields typeof 'object'.

Related errors


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