TheAlgorithms/JavaScript · error · TypeError
Input should be a string
Error message
Input should be a string
What it means
Guard in countVowels. The function counts vowels via str.match(/[aeiou]/gi) and first requires the input to be a string, throwing TypeError otherwise. This protects .match() from non-string values.
Source
Thrown at String/CountVowels.js:12
/**
* @function countVowels
* @description Given a string of words or phrases, count the number of vowels.
* @param {String} str - The input string
* @return {Number} - The number of vowels
* @example countVowels("ABCDE") => 2
* @example countVowels("Hello") => 2
*/
const countVowels = (str) => {
if (typeof str !== 'string') {
throw new TypeError('Input should be a string')
}
const vowelRegex = /[aeiou]/gi
const vowelsArray = str.match(vowelRegex) || []
return vowelsArray.length
}
export { countVowels }
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a string; default to '' when the source may be missing (countVowels('') returns 0).
- Validate typeof at the call site.
- Coerce with String(value) only after a null/undefined check.
Example fix
// before countVowels(input) // after countVowels(typeof input === 'string' ? input : '')
Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof str !== 'string') {
throw new TypeError('str must be a string')
}
countVowels(str) Type guard
const isString = (v) => typeof v === 'string'
Try / catch
try {
countVowels(input)
} catch (e) {
if (e instanceof TypeError) { /* not a string */ } else throw e
} Prevention
- Default optional fields to ''.
- Coerce with String() after a null check.
- Validate at the boundary.
When it happens
Trigger: Calling countVowels(undefined), countVowels(null), countVowels(42), countVowels({}). Any input where typeof !== 'string'.
Common situations: Optional field omitted from a payload; value coerced to a number earlier; array passed instead of a joined string.
Related errors
- Argument is not a string.
- Argument is not a string.
- The first param should be a string
- The second param should be a boolean
- Input should be a string
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/def5e5eb5173626d.
Report an issue: GitHub.