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

  1. Pass a string; default to '' when the source may be missing (countVowels('') returns 0).
  2. Validate typeof at the call site.
  3. 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

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


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