TheAlgorithms/JavaScript · error · TypeError
The first param should be a string
Error message
The first param should be a string
What it means
First-parameter guard in checkWordOccurrence. The function splits a sentence into words and counts occurrences. Before doing so, it requires the first argument (str) to be a string; anything else throws TypeError. This protects the later .split() and .reduce() calls.
Source
Thrown at String/CheckWordOccurrence.js:10
/**
* @function checkWordOccurrence
* @description - this function count all the words in a sentence and return an word occurrence object
* @param {string} str
* @param {boolean} isCaseSensitive
* @returns {Object}
*/
const checkWordOccurrence = (str, isCaseSensitive = false) => {
if (typeof str !== 'string') {
throw new TypeError('The first param should be a string')
}
if (typeof isCaseSensitive !== 'boolean') {
throw new TypeError('The second param should be a boolean')
}
const modifiedStr = isCaseSensitive ? str.toLowerCase() : str
return modifiedStr
.split(/\s+/) // remove all spaces and distribute all word in List
.reduce((occurrence, word) => {
occurrence[word] = occurrence[word] + 1 || 1
return occurrence
}, {})
}
export { checkWordOccurrence }
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Pass a string sentence; if the source may be absent, coalesce to ''.
- Validate the first argument's type at the call site before invoking.
- If accepting arrays, join first: arr.join(' ').
Example fix
// before checkWordOccurrence(maybeSentence) // after checkWordOccurrence(typeof maybeSentence === 'string' ? maybeSentence : '')
Defensive patterns
Strategy: type-guard
Validate before calling
if (typeof str !== 'string') {
throw new TypeError('str must be a string')
}
checkWordOccurrence(str) Type guard
const isString = (v) => typeof v === 'string'
Try / catch
try {
checkWordOccurrence(sentence)
} catch (e) {
if (e instanceof TypeError && /first param/i.test(e.message)) { /* handle */ } else throw e
} Prevention
- Coalesce nullable inputs: str ?? ''.
- Join arrays before passing.
- Keep a unit test that passes null to confirm your guard.
When it happens
Trigger: Calling checkWordOccurrence(null), checkWordOccurrence(123), checkWordOccurrence(), or checkWordOccurrence({text:'a b'}). Any first arg where typeof !== 'string'.
Common situations: Forgotten argument when refactoring a call site; reading textarea value that was never set; a payload field that is null instead of an empty string; an array passed where a joined string was expected.
Related errors
- The second param should be a boolean
- the param should be string
- 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/2d793c5eaeb90ee0.
Report an issue: GitHub.