TheAlgorithms/JavaScript · error · Error

The param should be a nonempty string

Error message

The param should be a nonempty string

What it means

Second guard in maxCharacter. After the typeof check passes, if str is falsy (empty string '', but also NaN/0/false are already blocked by the typeof check, so in practice only '') the function throws a plain Error. The intent is to reject empty input because there is no 'max' character to return.

Source

Thrown at String/MaxCharacter.js:13

/**
 * @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) {
      max = { char, occur }
    }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Guard for emptiness before calling: only call when str.length > 0.
  2. Trim and re-check if whitespace-only input should be treated as empty.
  3. Provide a meaningful fallback (skip the call) instead of letting it throw.

Example fix

// before
maxCharacter(text)

// after
const t = (typeof text === 'string' ? text : '').trim()
if (t.length) maxCharacter(t)
Defensive patterns

Strategy: validation

Validate before calling

const text = (typeof str === 'string' ? str : '').trim()
if (text.length === 0) {
  throw new Error('str must be a non-empty string')
}
maxCharacter(text)

Type guard

const isNonEmptyString = (v) => typeof v === 'string' && v.trim().length > 0

Try / catch

try {
  maxCharacter(str)
} catch (e) {
  if (e instanceof Error && /nonempty/i.test(e.message)) { /* provide default or skip */ } else throw e
}

Prevention

When it happens

Trigger: Calling maxCharacter(''), maxCharacter('') with any ignorePattern. Only an empty string reaches this branch.

Common situations: Empty form input forwarded without trimming/validation; a string field that is '' by default; whitespace stripped down to '' before the call; an array joined to '' .

Related errors


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