TheAlgorithms/JavaScript · error · TypeError

Argument should be string

Error message

Argument should be string

What it means

Guard in countSubstrings. The function counts non-overlapping occurrences of a substring and requires BOTH arguments to be strings; if either str or substring fails typeof, it throws TypeError. The single shared message does not indicate which argument was invalid.

Source

Thrown at String/CountSubstrings.js:13

/**
 * @function countSubstrings
 * @description Given a string of words or phrases, count the occurrences of a substring
 * @param {String} str - The input string
 * @param {String} substring - The substring
 * @return {Number} - The number of substring occurrences
 * @example countSubstrings("This is a string", "is") => 2
 * @example countSubstrings("Hello", "e") => 1
 */

const countSubstrings = (str, substring) => {
  if (typeof str !== 'string' || typeof substring !== 'string') {
    throw new TypeError('Argument should be string')
  }

  if (substring.length === 0) return str.length + 1

  let count = 0
  let position = str.indexOf(substring)

  while (position > -1) {
    count++
    position = str.indexOf(substring, position + 1)
  }

  return count
}

export { countSubstrings }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Ensure both arguments are strings; default the substring when optional.
  2. Validate both typeof str === 'string' && typeof sub === 'string' at the call site.
  3. If substring may be empty, note empty returns str.length+1 by design.

Example fix

// before
countSubstrings(haystack, needle)

// after
if (typeof haystack === 'string' && typeof needle === 'string') {
  countSubstrings(haystack, needle)
}
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof str !== 'string' || typeof substring !== 'string') {
  throw new TypeError('both str and substring must be strings')
}
countSubstrings(str, substring)

Type guard

const areStrings = (a, b) => typeof a === 'string' && typeof b === 'string'

Try / catch

try {
  countSubstrings(haystack, needle)
} catch (e) {
  if (e instanceof TypeError) { /* one of the args was not a string */ } else throw e
}

Prevention

When it happens

Trigger: Calling countSubstrings(null, 'is'), countSubstrings('text', undefined), countSubstrings(123, '1'), countSubstrings('text', ['a']). Either argument non-string.

Common situations: An optional substring parameter omitted (becomes undefined); a haystack read from a source that returned null; passing a regex where a string was expected.

Related errors


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