{"record":{"id":"def5e5eb5173626d","repo":"TheAlgorithms/JavaScript","slug":"input-should-be-a-string-def5e5","errorCode":null,"errorMessage":"Input should be a string","messagePattern":"Input should be a string","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"String/CountVowels.js","lineNumber":12,"sourceCode":"/**\n * @function countVowels\n * @description Given a string of words or phrases, count the number of vowels.\n * @param {String} str - The input string\n * @return {Number} - The number of vowels\n * @example countVowels(\"ABCDE\") => 2\n * @example countVowels(\"Hello\") => 2\n */\n\nconst countVowels = (str) => {\n  if (typeof str !== 'string') {\n    throw new TypeError('Input should be a string')\n  }\n\n  const vowelRegex = /[aeiou]/gi\n  const vowelsArray = str.match(vowelRegex) || []\n\n  return vowelsArray.length\n}\n\nexport { countVowels }\n","sourceCodeStart":1,"sourceCodeEnd":22,"githubUrl":"https://github.com/TheAlgorithms/JavaScript/blob/5c39e87a9a31f279c60f830ad74a845e4788a517/String/CountVowels.js#L1-L22","documentation":"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.","triggerScenarios":"Calling countVowels(undefined), countVowels(null), countVowels(42), countVowels({}). Any input where typeof !== 'string'.","commonSituations":"Optional field omitted from a payload; value coerced to a number earlier; array passed instead of a joined string.","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."],"exampleFix":"// before\ncountVowels(input)\n\n// after\ncountVowels(typeof input === 'string' ? input : '')","handlingStrategy":"type-guard","validationCode":"if (typeof str !== 'string') {\n  throw new TypeError('str must be a string')\n}\ncountVowels(str)","typeGuard":"const isString = (v) => typeof v === 'string'","tryCatchPattern":"try {\n  countVowels(input)\n} catch (e) {\n  if (e instanceof TypeError) { /* not a string */ } else throw e\n}","preventionTips":["Default optional fields to ''.","Coerce with String() after a null check.","Validate at the boundary."],"tags":["string","validation","type-guard","vowels"],"backgroundTag":null,"analyzedSha":"5c39e87a9a31f279c60f830ad74a845e4788a517","analyzedAt":"2026-08-13T04:54:54.474Z","schemaVersion":2},"datasetVersion":"2026-08-13T09:17:06.757Z"}