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
- Pass a primitive string: ReverseStringIterative('hello').
- If the source may be non-string, coerce explicitly: ReverseStringIterative(String(value)).
- Unbox boxed strings: if (value instanceof String) value = value.valueOf().
- 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
- Never pass DOM elements or Buffers directly — read .value / call .toString().
- Avoid new String('...'); use primitive strings.
- Type-check at request boundaries before calling string utilities.
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
- The arg must be a valid, non empty string
- The given value is not a string
- The given value is not a string
- Email Address String Null or Empty.
- Invalid Input
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/76be01f08bbefce7.
Report an issue: GitHub.