TheAlgorithms/JavaScript · error · TypeError

Invalid Input

Error message

Invalid Input

What it means

Thrown as a TypeError by palindrome() when the input is not of type 'string'. The recursive implementation indexes into str with str[0], str[str.length-1], and str.slice(), all of which assume string semantics; passing a non-string would either behave incorrectly or throw a less descriptive error. The library uses a strict typeof check, so numbers, objects, and arrays are all rejected even if they 'look' palindromic.

Source

Thrown at Recursive/Palindrome.js:11

/**
 * @function Palindrome
 * @description Check whether the given string is Palindrome or not.
 * @param {String} str - The input string
 * @return {Boolean}.
 * @see [Palindrome](https://en.wikipedia.org/wiki/Palindrome)
 */

const palindrome = (str) => {
  if (typeof str !== 'string') {
    throw new TypeError('Invalid Input')
  }

  if (str.length <= 1) {
    return true
  }

  if (str[0] !== str[str.length - 1]) {
    return false
  } else {
    return palindrome(str.slice(1, str.length - 1))
  }
}

export { palindrome }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Coerce the input to a string first: palindrome(String(value)).
  2. Add a type guard at the boundary: if (typeof value === 'string') palindrome(value).
  3. If using TypeScript, annotate the parameter as str: string so the call site is checked at compile time.

Example fix

// before
const result = palindrome(userInput) // userInput may be a number

// after
const result = palindrome(String(userInput))
Defensive patterns

Strategy: type-guard

Validate before calling

function safePalindrome(value) {
  if (typeof value !== 'string') {
    throw new TypeError('Expected a string')
  }
  return palindrome(value)
}

Type guard

function isString(v) {
  return typeof v === 'string'
}

Try / catch

try {
  palindrome(input)
} catch (e) {
  if (e instanceof TypeError && e.message === 'Invalid Input') {
    return palindrome(String(input))
  }
  throw e
}

Prevention

When it happens

Trigger: Calling palindrome(12321), palindrome(['a','b','a']), palindrome(null), palindrome(undefined), or palindrome({0:'a'}). Numbers are the most common offender since 12321 'looks' like a numeric palindrome.

Common situations: Receiving untyped user input from a form field parsed as a number; JSON payloads where a field is sometimes a number; passing a value through several functions that lost its string typing.

Related errors


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