TheAlgorithms/JavaScript · error · TypeError
Input should be a string
Error message
Input should be a string
What it means
First guard in countLetters. The function counts each letter in a string and rejects non-string input with TypeError before any further processing. This is the outermost of three stacked guards (type, then special characters, then digits).
Source
Thrown at String/CountLetters.js:13
/**
* @function countLetters
* @description Given a string, count the number of each letter.
* @param {String} str - The input string
* @return {Object} - Object with letters and number of times
* @example countLetters("hello") => {h: 1, e: 1, l: 2, o: 1}
*/
const countLetters = (str) => {
const specialChars = /\W/g
if (typeof str !== 'string') {
throw new TypeError('Input should be a string')
}
if (specialChars.test(str)) {
throw new TypeError('Input must not contain special characters')
}
if (/\d/.test(str)) {
throw new TypeError('Input must not contain numbers')
}
const obj = {}
for (let i = 0; i < str.toLowerCase().length; i++) {
const char = str.toLowerCase().charAt(i)
obj[char] = (obj[char] || 0) + 1
}
return obj
}View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a string; if the source is missing, default to '' (note '' returns {}).
- Validate typeof at the call site.
- If the source is an array of chars, join first.
Example fix
// before countLetters(input) // after countLetters(typeof input === 'string' ? input : '')
Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof str !== 'string') {
throw new TypeError('str must be a string')
}
countLetters(str) Type guard
const isString = (v) => typeof v === 'string'
Try / catch
try {
countLetters(input)
} catch (e) {
if (e instanceof TypeError && /should be a string/i.test(e.message)) { /* handle */ } else throw e
} Prevention
- Default to '' when the source is optional.
- Validate typeof at the boundary.
- Document that countLetters is letters-only to prevent the next two errors.
When it happens
Trigger: Calling countLetters(undefined), countLetters(null), countLetters(42), countLetters(['a','b']). Any input where typeof !== 'string'.
Common situations: A function that previously received a string now receives a parsed JSON object; user input that was Number()-coerced earlier; an array passed where a flattened string was intended.
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 must not contain special characters
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/cd90e90ee74cdbbb.
Report an issue: GitHub.