TheAlgorithms/JavaScript · error · TypeError
Argument should be a string
Error message
Argument should be a string
What it means
First guard in maxCharacter. The function returns the most-frequent character (optionally ignoring a RegExp pattern) and requires str to be a string, throwing TypeError otherwise. This is the type branch; the emptiness branch is a separate error ([156]). Note the empty-string check (!str) is unreachable from a non-string because typeof short-circuits first.
Source
Thrown at String/MaxCharacter.js:11
/**
* @function maxCharacter
* @example - Given a string of characters, return the character that appears the most often. Example: input = "Hello World!" return "l"
* @param {string} str
* @param {RegExp} ignorePattern - ignore the char in str that is not required
* @returns {string} - char
*/
const maxCharacter = (str, ignorePattern) => {
// initially it's count only alphabets
if (typeof str !== 'string') {
throw new TypeError('Argument should be a string')
} else if (!str) {
throw new Error('The param should be a nonempty string')
}
// store all char in occurrence map
const occurrenceMap = new Map()
for (const char of str) {
if (!ignorePattern?.test(char)) {
occurrenceMap.set(char, occurrenceMap.get(char) + 1 || 1)
}
}
// find the max char from the occurrence map
let max = { char: '', occur: -Infinity }
for (const [char, occur] of occurrenceMap) {
if (occur > max.occur) {View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a string; default missing values to '' (note '' triggers the empty-string error, so pick a real default).
- Validate typeof at the call site.
- If the source is an array, join first.
Example fix
// before maxCharacter(maybeStr) // after if (typeof maybeStr === 'string' && maybeStr.length) maxCharacter(maybeStr)
Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof str !== 'string') {
throw new TypeError('str must be a string')
}
maxCharacter(str) Type guard
const isString = (v) => typeof v === 'string'
Try / catch
try {
maxCharacter(input)
} catch (e) {
if (e instanceof TypeError && /should be a string/i.test(e.message)) { /* not a string */ } else throw e
} Prevention
- Validate typeof at the boundary.
- Also guard for emptiness to avoid the follow-up [156] error.
- Join arrays before passing.
When it happens
Trigger: Calling maxCharacter(undefined), maxCharacter(null), maxCharacter(0), maxCharacter({}), maxCharacter([]). Any input where typeof !== 'string'.
Common situations: A field that is null on miss; a value coerced to a number; an array passed where a string was expected; refactoring that dropped the argument.
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/582aa0eaa93069d6.
Report an issue: GitHub.