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

  1. Pass a string sentence; if the source may be absent, coalesce to ''.
  2. Validate the first argument's type at the call site before invoking.
  3. 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

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


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/2d793c5eaeb90ee0. Report an issue: GitHub.