TheAlgorithms/JavaScript · error · TypeError
the param should be string
Error message
the param should be string
What it means
Guard in maxWord. The function finds the most-occurring word in a sentence and requires sentence to be a string, throwing TypeError otherwise. The parameter defaults to '', so omitting it is safe; only an explicitly non-string value throws.
Source
Thrown at String/MaxWord.js:12
// Given a sentence, return the most occurring word
/**
* @param {string} sentence - the sentence you want to find the most occurring word
* @returns {string} - the most occurring word
*
* @example
* - maxWord('lala lili lala'); // lala
*/
const maxWord = (sentence = '') => {
if (typeof sentence !== 'string') {
throw new TypeError('the param should be string')
}
if (!sentence) {
return null
}
const words = sentence.split(' ')
if (words.length < 2) {
return words[0]
}
const occurrences = {}
words.forEach((word) => {
occurrences[word.toLocaleLowerCase()] =
occurrences[word.toLocaleLowerCase()] + 1 || 1
})
const max = Object.keys(occurrences).reduce(View on GitHub (pinned to 5c39e87a9a)
Solutions
- Coerce null/undefined to '' before calling: sentence ?? ''.
- Validate typeof at the call site.
- Join arrays first: arr.join(' ').
Example fix
// before maxWord(maybeSentence) // after maxWord(typeof maybeSentence === 'string' ? maybeSentence : '')
Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof sentence !== 'string') {
throw new TypeError('sentence must be a string')
}
maxWord(sentence) Type guard
const isString = (v) => typeof v === 'string'
Try / catch
try {
maxWord(sentence)
} catch (e) {
if (e instanceof TypeError) { /* not a string */ } else throw e
} Prevention
- Coalesce null to '': sentence ?? '' (the default only catches undefined).
- Join arrays before passing.
- Validate typeof at the boundary.
When it happens
Trigger: Calling maxWord(null), maxWord(42), maxWord(['a','b']), maxWord({}). Any explicit non-string argument. (maxWord() and maxWord(undefined) do NOT throw because the default applies.)
Common situations: A source that returns null on miss instead of undefined (bypassing the default); a number passed where a sentence string was expected; an array passed where a joined string was intended.
Related errors
- The first param should be a string
- The second param should be a boolean
- Argument is not a string.
- Argument is not a string.
- Input should be a string
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/d6c91b54116e60e6.
Report an issue: GitHub.