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 reverseWords() in String/ReverseWords.js when typeof str !== 'string'. A TypeError raised before the .split(/\s+/) pipeline runs, because split only exists meaningfully on strings and the reduceRight builds a new string. Only the type is checked, so an empty string '' is accepted and returns '' after trim.
Source
Thrown at String/ReverseWords.js:8
/**
* @function reverseWords
* @param {string} str
* @returns {string} - reverse string
*/
const reverseWords = (str) => {
if (typeof str !== 'string') {
throw new TypeError('The given value is not a string')
}
return str
.split(/\s+/) // create an array with each word in string
.reduceRight((reverseStr, word) => `${reverseStr} ${word}`, '') // traverse the array from last & create an string
.trim() // remove the first useless space
}
export default reverseWords
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a string primitive: reverseWords('hello world').
- Coerce at the boundary: reverseWords(String(value)).
- Verify the upstream data shape — if value is sometimes non-string, fix the producer (e.g. schema-validate request bodies).
- If you intentionally store text in an object, read the right property before passing it.
Example fix
// before const r = reverseWords(req.body.title) // title is sometimes a number in malformed payloads // after const r = reverseWords(typeof req.body.title === 'string' ? req.body.title : String(req.body.title ?? ''))
Defensive patterns
Strategy: type-guard
Validate before calling
function reverseWordsSafe(v) {
if (typeof v !== 'string') v = String(v ?? '')
return reverseWords(v)
} Type guard
const isString = (v) => typeof v === 'string'
Try / catch
try { reverseWords(s) } catch (e) { if (e instanceof TypeError && /not a string/.test(e.message)) s = String(s); else throw e } Prevention
- Coerce all incoming form/JSON fields to strings at the boundary.
- Read .value from DOM inputs, never the element itself.
- Validate request bodies with a schema that declares string fields.
When it happens
Trigger: Calling reverseWords(42), reverseWords(null), reverseWords(undefined), reverseWords(['hello world']), reverseWords({ text: 'hi' }). Empty string reverseWords('') does NOT throw — it returns ''.
Common situations: Reading req.body fields that arrived as a number from JSON; passing a Node Buffer; forgetting to .toString() a value read from a stream; mixing up argument order so an options object lands in str.
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/0da2bd8620e7c4cb.
Report an issue: GitHub.